Conexion Singleton
public class DBConnection {
private static DBConnection instance = null;
private Connection connection;
protected DBConnection(){
this.conectaPGSQL();
}
public Connection getConnection(){
return this.connection;
}
public static DBConnection getInstance(){
if(instance == null){
System.out.println("Instancia nueva");
instance = new DBConnection();
}
return instance;
}
private Connection conectaPGSQL(){
try{
this.connection = //aqui va el condigo de tu driver manager para la conexion
if (this.connection != null) {
} else {
JOptionPane.showMessageDialog(null, "Falló al conectar la Base de datos","Connection Error", JOptionPane.ERROR_MESSAGE);
}
return this.connection;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return null;
}
}
}
Ejemplo
String showTableSQL = "SELECT * FROM llamadas";
DBConnection db = DBConnection.getInstance();
try {
Connection conn = conexiondb.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(showTableSQL);
while (rs.next()) {
// Obtenemos el modelo del JTable
model = (DefaultTableModel) table.getModel();
// Agregamos las filas al JTable
model.addRow(new Object[]{
Integer.toString(rs.getInt(1)),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
Integer.toString(rs.getInt(6)),
Double.toString(rs.getDouble(7))
});
}
rs.close();
st.close();
conn.close();
} catch (Exception e) { e.printStackTrace(); }