I'm currently building a small applciation which uses JDBC and MySQL.
I have this DB class. Currently it only has a main method which connects, and then returns something. Now this is working correctly. But I would like to change it to this:
DB Class with a constructor. Multiple methods which call different SQL query's for example I would want to call a user like this.
db.user('John');
So what do I want to prevent: Having to connect each time I make a new method.
Sorry if the question might be a bit unclear. I'm a new JDBC user.
package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
//ToDo Add these credentials leter to a main config file.
private static String connectionUrl = "jdbc:mysql://localhost:3306/tvh_jdbctesting";
private static String connectionUser = "root";
private static String connectionPassword = "root";
private static String jdbc = "com.mysql.jdbc.Driver";
DB(){
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName(jdbc).newInstance();
//Makes connection with the provided credentials.
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM test");
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String wachtwoord = rs.getString("wachtwoord");
System.out.println(id + name + wachtwoord);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}