I got three classes for MySQL Database access/manipulation:
Conector
. It has got methods for connecting, disconnecting, querying and updating db.ConectorCliente
. It simply extends first and got its constructor receivinguser
,password
,host
,port
anddb
.- I have written has several different methods per each DB, depending on data which will be needed to be selected, updated or deleted.
These are my classes in the mentioned order:
First class
public class Conector {
private Connection connection = null;
private Statement statement = null;
private ResultSet set = null;
String host;
String port;
String login;
String password;
String url;
public Conector (String login, String password, String db, String host, String port) {
this.login = login;
this.password = password;
this.host = host;
this.port = port;
url = "jdbc:mysql://"+host+":"+port+"/"+db;
Conectar ();
}
public void Desconectar () {
connection = null;
}
private void Conectar() {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
} catch (SQLException ex) {
Logger.getLogger(Conector.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(url, login, password);
statement = connection.createStatement();
}
catch (SQLException e) {
Logger logger = Logger.getLogger(Conector.class.getName());
logger.log(Level.SEVERE, e.getSQLState(), e);
}
}
public ResultSet Query(String query){
try {
statement = connection.createStatement();
set = statement.executeQuery(query);
}
catch (Exception e) {
System.out.println("Exception in query method:\n" + e.getMessage());
}
return set;
}
public boolean Update (String update) {
try {
statement = connection.createStatement();
statement.executeUpdate(update);
}
catch (SQLException e) {
System.out.println("Exception in update method:\n" + e.getMessage());
return false;
}
return true;
}
public void cierraConexion(){
try {
connection.close();
connection = null;
}
catch(Exception e) {
System.out.println("Problema para cerrar la conexión a la base de datos ");
}
}
}
Second class
public class ConectorCliente extends Conector {
public ConectorCliente(String login, String password, String db, String host, String port) {
// Con super llamamos y ocupamos el constructor de la clase padre
super(login, password, db, host, port);
}
}
Example of third class
public class InteraccionDB {
private static final ConectorCliente conector = new ConectorCliente("user", "pass","db", "127.0.0.1", "3306");
public static int obtenerNumRegistros() {
ResultSet resultado = conector.Query("SELECT COUNT(*) FROM tweets;");
try {
while (resultado.next()) {
return resultado.getInt("COUNT(*)");
}
} catch (SQLException ex) {
Logger.getLogger(InteraccionDB.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
public static void insertarTweet(String id) {
conector.Update("INSERT INTO tweets (id) VALUES ('"+id+"')");
}
public static void eliminarTweet(String id) {
conector.Update("DELETE FROM tweets WHERE id = '"+id+"'");
}
public static HashMap<String, Integer> obtenerHoraTweet(String id) {
HashMap<String, Integer> resultados = new HashMap<>();
ResultSet resultado = conector.Query("SELECT hora, min FROM tweets WHERE id = '"+id+"'");
try {
while (resultado.next()) {
resultados.put("Hora", resultado.getInt(1));
resultados.put("Minuto", resultado.getInt("min"));
}
} catch (SQLException ex) {
Logger.getLogger(InteraccionDB.class.getName()).log(Level.SEVERE, null, ex);
}
return resultados;
}
public static ArrayList<String> obtenerIdsRetweets(int retweets) {
ArrayList<String> resultados = new ArrayList<>();
ResultSet resultado = conector.Query("SELECT id FROM tweets WHERE retweets > "+retweets);
try {
while (resultado.next()) {
resultados.add(resultado.getString("id"));
}
} catch (SQLException ex) {
Logger.getLogger(InteraccionDB.class.getName()).log(Level.SEVERE, null, ex);
}
return resultados;
}
}
In my case, I prefer to make third class to return structures like ArrayList
's or HashTable
's making code cleaner at invocation side.
I care to improve:
- Exception handling (I know I'm not doing nothing for it so far)
- Going for Interfaces
- Security
- Java / OOP stuffs