Note - this follows my question here: http://stackoverflow.com/questions/2983685/jdbc-does-the-connection-break-if-i-lose-reference-to-the-connection-object
Now i have a created a class so i can deal with JDBC easily for the rest of my code -
public class Functions {
private String DB_SERVER = "";
private String DB_NAME = "test";
private String DB_USERNAME = "root";
private String DB_PASSWORD = "password";
public Connection con;
public PreparedStatement ps;
public ResultSet rs;
public ResultSetMetaData rsmd;
public void connect()
throws java.io.FileNotFoundException, java.io.IOException,
SQLException, Exception {
String[] dbParms = Parameters.load();
DB_SERVER = dbParms[0];
DB_NAME = dbParms[1];
DB_USERNAME = dbParms[2];
DB_PASSWORD = dbParms[3];
// Connect.
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://"
+ DB_SERVER + "/"
+ DB_NAME, DB_USERNAME, DB_PASSWORD);
}
public void disconnect() throws SQLException {
// Close.
con.close();
}
}
As seen Parameters.load() refreshes the connection parameters from a file every-time, so that any changes to the same may be applied on the next immediate connection.
An example of this class in action -
public static void add(String NAME)
throws java.io.FileNotFoundException, java.io.IOException, SQLException, Exception {
Functions dbf = new Functions();
dbf.connect();
String query = "INSERT INTO " + TABLE_NAME + "(" +
"NAME" +
") VALUES(?)";
PreparedStatement ps = dbf.con.prepareStatement(query);
ps.setString(1, NAME);
ps.executeUpdate();
dbf.disconnect();
}
Now here is the problem - for adding a record to the table above, the add() method will open a connection, add the record - and then call disconnect() .
What if i want to get the ID of the inserted record after i call add() -like this :
Department.add("new dept");
int ID = getlastID();
Isn't it possible that another add() was called between those two statements?