Is the following code the most effective way to connect to a db or would a
java bean be better?
import java.sql.*;
import javax.servlet.http.*;
public class ConnectionBean implements HttpSessionBindingListener {
private Connection connection;
private Statement statement;
private static final
String driver="org.gjt.mm.mysql.Driver";
private static final String dbURL="jdbc:mysql://bang.zeroslope.com/project";
private static final String login="coursepoller";
private static final String password="course";
public ConnectionBean() {
try {
Class.forName(driver);
connection = DriverManager.getConnection(dbURL,login,password);
statement = connection.createStatement();
} catch (ClassNotFoundException e) {
System.err.println("ConnectionBean: driver unavailable: "+e);
connection = null;
} catch (SQLException e) {
System.err.println("ConnectionBean: driver not loaded: "+e);
connection = null;
}
}
public Connection getConnection() {
return connection;
}
public ResultSet executeQuery(String sql) throws SQLException {
return statement.executeQuery(sql);
}
public int executeUpdate(String sql) throws SQLException {
return statement.executeUpdate(sql);
}
public void valueBound(HttpSessionBindingEvent event) {
System.err.println("ConnectionBean: in the valueBound method");
try {
if (connection == null | | connection.isClosed()) {
connection = DriverManager.getConnection(dbURL,login,password);
statement = connection.createStatement();
}
} catch (SQLException e) { connection = null; }
}
public void valueUnbound(HttpSessionBindingEvent event) {
try {
connection.close();
} catch (SQLException e) { }
finally {
connection = null;
}
}
protected void finalize() {
try {
connection.close();
} catch (SQLException e) { }
}
public static void main(String[] args) {
ConnectionBean connectionBean1 = new ConnectionBean();
}
}