I've recently learned how to use MySQL to store/retrieve data. I've created a MySQLManager class for creating connections and executing querys/updates. Would this be an efficient way to do so?
This is my MySQLManager class:
public class MySQLManager {
private String host;
private String port;
private String database;
private String user;
private String password;
public MySQLManager(String host, String port, String database, String user, String password){
this.host = host;
this.port = port;
this.database = database;
this.user = user;
this.password = password;
}
private Connection createConnection(){
Connection connection;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user, password);
return connection;
} catch (SQLException e) {
System.out.println("Could not connect to MySQL server! because: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found!");
}
return null;
}
public ResultSet executeQuery(String query){
Connection connection = createConnection();
Statement statement = null;
ResultSet set = null;
try {
statement = connection.createStatement();
set = statement.executeQuery(query);
return set;
} catch (SQLException e) {
e.printStackTrace();
} finally { //Close in order: ResultSet, Statement, Connection.
try { set.close(); } catch (Exception e) { }
try { statement.close(); } catch (Exception e) { }
try { connection.close(); } catch (Exception e) { }
}
return null;
}
public void executeUpdate(String update){
Connection connection = createConnection();
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(update);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try { statement.close(); } catch (Exception e) { }
try { connection.close(); } catch (Exception e) { }
}
}
}
I would then use this to execute querys/updates:
MySQLManager manager = new MySQLManager(host, port, database, user, pass);
manager.executeQuary("SELECT * FROM table;");
manager.executeUpdate("Some update;");
Are there any better ways to doing this? Is there anything I can improve in my code?