querying remote mysql database from java application - java

I want to be able to able to get a connection to a remote mysql database from a hava application. That is suppose i have a database server in london with user table, and another database server in paris with a product table and i want to be able from anywhere to get connection to these 2 databases and perform operations on them separately from a java application. My hope is to hide details such as ip address where the servers are located. I just want a kind of handle that abstract the lower level details for each of the servers and using this handle get a connection in a java application. Any help will be highly appreciated

I think that this works for me, if it is what you are searching for:
try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database, username, password);
Statement stm = connection.createStatement();
stm.execute("SOME PIECE of SQL CODE HERE");
} catch (SQLException e) {
}
Talking about address and that kind of stuff, if just you will have acess to the application, there's no problem to have your mysql data in the code. But if you will send this code for another people, you might need to create a client/server based application to avoid losing your credentials.

Related

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Java - How to fetch email address from phpMyAdmin and send using javamail

I've designed ForgotMyPassword.java jFrame Form on NetBeans IDE 8.2
wherein I'm using phpMyAdmin for fetching the E-Mail Address of registered users from it and sending it to their E-Mail Addresses through MYSQL Database using JavaMail
I basically want to fetch the E-Mail Address of registered users from it and send it to their E-Mail Addresses through MYSQL Database using JavaMail as One Time Password (OTP) recovery option
Here's the source code :
String username = usrnmfield.getText();
String email = emailID.getText();
String[] to = {"emailaddr#gmail.com"};
Connection conn=null;
PreparedStatement pstn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection db = DriverManager.getConnection("jdbc:mysql://localhost:3307/app" , "xxxx" , "xxxx");
pstn=db.prepareStatement("select * from register where USERNAME=? and EMAIL=?");
pstn.setString(1,username);
pstn.setString(2,email);
ResultSet i=pstn.executeQuery();
if(i.next())
{
if(JavaMail.send
("abc#gmail.com",
"xxxx",
to,
"Hello world",
"Thank you for reading my post"))
{
JOptionPane.showMessageDialog(null , " Please Check out your Inbox for any Password sent by us to you ");
}
}
else if (usrnmfield != i && emailID != i)
{
JOptionPane.showMessageDialog(null, "Wrong Username or E-Mail ID");
}
} catch(HeadlessException | ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
Some remarks and adjustements that could help:
Concerning your application design you should strongly consider another architecture. It is far not recommended to let a client (desktop) app work directly with the SQL database for security matters. Implementing the whole security on the client-side is obviously a bad idea (and will get bypassed easily) as well as it will be unmanageable. Consider using a centralized secure database on a distant also secure server that provides state-of-the-art authentication and authorization mecanisms (eg. through REST-API over HTTPS). Server-side security frameworks include Keycloak, SpringSecurity, Apache Shiro, JaaS... By searching the Web you will see that your design is not so common. Moreover for OTP the use of a Web server or simply remote exchanges seem obvious (and you will need them). You may also consider implement logging through a centralized LDAP server.
Name your fields in the select statement. Eg. "select password from register where ..." so that you know what you expect in order OR use the field name when using select *:
ResultSet rs = ...
String myValue = rs.getString(1);
String myValueBis = rs.getString("password");
Always surround your database queries with a try-finally block in order to close your ResultSet, the prepared statement and eventually the connection (if not reused) and preferably in this order.
I don't see the purpose of this condition:
else if (usrnmfield != i && emailID != i) { ...
You are comparing text fields against a ResultSet but neither the value contained in the text nor the values of the current row of the ResultSet (cf. 1). This makes no sense.
If you want to allow you user to retrieve its password based on its username or its e-mail you should consider using an "OR" (instead of "and") in your SQL statement.
When using JavaMail you must make sure that your Session contains enough information to send an email. It is generally the first step in any JavaMail app to create a javax.mail.Session object. So you need to configure the smtp server or relay, eventually the port and authentication. As you don't show the code of your JavaMail class I suggest you put it in your original question if you have any issue about it and clarify what is the problem (if any).
Generally speaking if you consider using this app for commercial use or some serious purpose you should also quickly think about storing your passwords in an encrypted way (eg. as SHA-256). And also think about not sending the password via E-mail (it will out come naturally if you only store the hash of the users' password...) but instead propose them a secure way to reset/renew it.
I think you should update your question with more code (more finalized and cleaner preferably) and be more precise about your issue. I would not be surprized that a moderator flags your question as too "general" or obscure.

Does Connection Pooling makes Java Swing Application works faster for remote MySQL database

I have Created an Java Swing Application with MySQL as the database, Now i am hosting my MySQL database online and Swing Application will be stored locally, Now in order to experiment i have hosted my database i.e MySQL database on https://www.freemysqlhosting.net/ account as it allows free hosting for certain period, Also Connection is successfull and works but the application works too slow suppose if i have to search any entry from the swing aplication from the oline hosted database it works too slow,it is happening like i have to press any key or button and has to wait for the processing of the transaction. Does connection pooling technique will solve the performance issues, If yes which is best one and if not what can i do to solve this. Please Help
Below is the code which i have written to make database transactions and i am doing this everytime i make a database access
public ArrayList<ChargeSheet> readByAllCompanyInfo(String cityname)
{
ArrayList<ChargeSheet> list = new ArrayList<ChargeSheet>();
con=db.getConnection();
try{
pst = con.prepareStatement("select * from tblcompanyinformation where companyname = ?");
pst.setString(1,cityname);
rs = pst.executeQuery();
while(rs.next()){
ChargeSheet clientInformation=new ChargeSheet();
clientInformation.setRecieptno(rs.getInt(2));
clientInformation.setPresentdate(rs.getString(3));
clientInformation.setCompanyname(rs.getString(4));
clientInformation.setPhone(rs.getString(5));
list.add(clientInformation);
}
}
catch(SQLException ex){
setLastError(ex.getMessage());
}
finally{
db.closeConnection();
}
return list;
}
With that code, it is likely that using a connection pool will improve performance. Especially if you are using SSL-enabled connections.
(Of course, this assumes that you use the same pool for connecting.)
If yes which is best one ....
Recommendations are Off-Topic for StackOverflow, but I'm sure you could find a website that lists and compares some popular alternatives.

How to specify database in SQL query with Java

I am trying to upload some data to a MySQL database using Java, as I'm working on an Android app. So far, this code compiles and runs, but is uploading nothing to my database. I assume because I'm not accessing the database "streakly" anywhere, but when I've searched around for a way to solve this I haven't found anything.
Snippet of code I'm trying to upload
String addStreakName = chooseName.getText().toString();
String addCategory = prefs.getString("Category", "");
String addToday = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
if(prefs.getInt("todayOrChosen", 1) == 1){
int addStartedZero = 0;
streakList.add(new Streak(addStreakName, addCategory, addToday, addStartedZero));
try {
Connection con = DriverManager.getConnection("127.0.0.1", "[myusername]", "[mypassword]");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO `users`(userId, addStreakName,addCategory,addToday,addStartedZero) VALUE ('"+addStreakName+"', '"+addCategory+"', '"+addToday+"', '"+addStartedZero+"', '"+userID+"')");
} catch (SQLException e) {
e.printStackTrace();
}
}
You are trying to connect to localhost, which in your case is the android device. I am pretty sure there's no MySQL server running on your device, thus the problem you see. You can probably connect to a MySQL server using JDBC driver, but I really wouldn't recommend it. Mobile apps live on users devices, and having direct access to your database server is not such a good idea. If you need a local database, you can use SQLite, Couchbase Lite, Firebase, Realm, etc. If you want to then synchronize with a server, you can either implement an application server and sync via REST for example, or use a solution like Couchbase Lite+Sync Gateway or Google's Firebase
Regards,
Vladimir

How to connect to a database that requires password without exposing the password?

I am creating an application and I need to connect to a database. The database requires login/password so the application can do operations like select and insert.
In the application I need to connect to the database using login and password, so the application is free to do some tasks on the database. My question is: how do I store and use a password to connect to the database without exposing the password?
I can't simply use a hash or encryption to store the password because the database must recognize the password (I think most or all databases must receive password as plain text).
.
.
Note: The connection is made by the application. No human input to do the connection.
(Edit)More info about the application: it is a web application using servlets/jsp. The database is on the same server of the application. The user for the application is a default user without complete admin powers, but it may insert/delete rows and do most things that involve queries and data modification in tables.
The usual way this is done is to externalize the username/password to a property/config file which is read at runtime (whether or not you use native JDBC/JNDI/CDI/J2EE datasource/etc).
The file is protected via the O/S security by the sysadmins.
The O/S has better tools for protection than app code.
You can use jasypt for the encryption.And store the username and password to datasource.properties file.
public Connection getConnection() throws IOException{
try{
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword("jasypt");
Properties props = new EncryptableProperties(encryptor);
props.load( this.getClass().getResourceAsStream("datasource.properties") );
String driver = props.getProperty("datasource.driver");
String url = props.getProperty("datasource.url");
String userName = props.getProperty("datasource.userName");
String password = props.getProperty("datasource.password");
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
conn.setAutoCommit(false);
return conn;
} catch(ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch(SQLException e) {
e.printStackTrace();
return null;
}
}
You should use a config file for this. use spring with JDBC to make your life easier!
http://www.youtube.com/watch?v=f-k823MZ02Q
Checkout the above awesome tutorial on the Spring framework and using JDBC. Watch all of his JDBC and spring tutorials.
BTW, he covers how to store passwords in config files and wire beans etc.. Hope this helps.
If it's a web app, deploy it on a Java EE app server and connect using a JNDI resource. Only the admin who set up the JNDI data resource needs to know about the credentials needed to connect. Users and developers don't even have to know them; just the JNDI lookup name.
It's not possible to completely eliminate the need for someone besides the database owner to know the username and password, but it is possible to restrict that knowledge to the app server owner.
You are also well advised to create separate credentials just for that application and GRANT it the minimum access and permissions needed to accomplish its tasks. There should be no knowledge of system tables or any other resources outside the province of the application. IF DELETE permission isn't necessary, don't grant it. If access should only be read only, that's what you should GRANT to that credential.

Categories