I'm looking to create a static database connection from when the application opens and then the connection is killed when the application closes which is working grand.
My question is how can I keep the connection static within the database class?
When I call checkPassword() from a login class it always returns false due to there being no valid connection to the database(conn) even though the database connection was opened in the static main.
Any help greatly appreciated.
public class database {
Server hsqlServer = null;
static Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
String query = null;
public void startDatabase() {
// Start database process
hsqlServer = new Server();
hsqlServer.setLogWriter(null);
hsqlServer.setSilent(true);
hsqlServer.setDatabaseName(0, "testdb");
hsqlServer.setDatabasePath(0, "file:testdb");
hsqlServer.start();
}
public void stopDatabase() {
// Stop database process
try {
hsqlServer.stop();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, config.DATABASE_ERROR);
System.exit(0);
}
}
public void connOpen() {
try {
Class.forName("org.hsqldb.jdbcDriver");
conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb","SA","");
}
catch(Exception e) {
// error opening database connection
}
}
public void connClose() {
try {
conn.close();
}
catch(Exception e) {
// error closing database connection
}
}
public boolean checkPassword(String username,char[] password) {
boolean validPassword = false;
try {
query = "SELECT id,username,password FROM users";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
rs.next();
System.out.println("ID: " + rs.getInt(1) + "\n");
}
catch(SQLException e) {
// error checking users password
}
return validPassword;
}
}