I’m rather new to the world of Java, and i am not quite sure how to do this.
I have a MySQL class which extracts a table just fine, and prints it to the console. However, i need to do custom SQL queries from another class, and i can’t figure out how to do that. Anyone who can help out?
Here’s the mysql class:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class mySQL {
public static void main(String[] args) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://host:port/database";
String user = "user";
String password = "password";
try {
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM NFT_users");
rs = pst.executeQuery();
con = DriverManager.getConnection(url, user, password);
while (rs.next()) {
System.out.print(rs.getInt(1));
System.out.print(": ");
System.out.println(rs.getString(2));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(mySQL.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(mySQL.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
Your problem is not about
SQL, it is about software design.Consider a class whose entire existence is about giving you access to data. It would do all the connection stuff (
private void loadConnection), and then had methods likeArrayList<User> getUsers().Then, when you need your list of
Users, all you would do is just domyDatabaseObject.getUsers()or, in another situation, domyDatabaseObject.getOtherObjects(). But none of the rest of your code would know anything about SQL or connecting to the DB.If you want to do more than very simple database access, you should consider learning Hibernate. Wikipedia link. If you’ve ever been reading through questions on this site and wondered what Hibernate is, it’s exactly the tool that does this.
As far as how to do this yourself, just put the connection code in the constructor, save the connection to a field, and have the methods described above do the queries (preferably using
PreparedStatement).