I have point of sale (POS) software and in my billing module I make the respective connection to the database every time I go to save an invoice and once the invoice is saved I close the connection.
I do it like this
for (i=0; i< cantidad_productos; i++){
Connection con = null;
con = DB_consultas_R_D.getConexion();
PreparedStatement psql = null
String SSQL = "INSERT INTO tabla (id,columna1,colmna2) values (1,'hola','mundo');"
try {
psql = con.prepareStatement(SSQL);
psql.executeUpdate();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error al intentar almacenar la información factura detallas:\n"
+ e, "Error en la operación", JOptionPane.ERROR_MESSAGE);
}
try {
psql.close();
con.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error al intentar almacenar la información factura detallas:\n"
+ ex, "Error la cerrar conexion", JOptionPane.ERROR_MESSAGE);
}
}
getConnection method that returns a connection to the database.
public static Connection getConexion() {
try {
consulta_database_name(new File("").getAbsolutePath() + "/src/database_name.txt");
consulta_database_ip(new File("").getAbsolutePath() + "/src/ip.txt");
url = "jdbc:postgresql://" + ip + ":5432/" + database_name;
} catch (Exception e) {
System.out.println("Error en getConexion: "+e);
}
Connection cn = null;
try {
Class.forName("org.postgresql.Driver");
cn = DriverManager.getConnection(url, usuario, contrasenia);
} catch (Exception e) {
System.out.println(String.valueOf(e));
JOptionPane.showMessageDialog(null, "Error de conexión a la base de datos:\n " + e);
}
return cn;
}
So I don't know if the way I do it is fine and how recommendable it is to leave the connection open all day at work.
Currently I close the connection after saving each record, also it presents me with a little delay when I save from intranet connection.
Thank you