What is the best place to put PreparedStatement initialization, when i want to use it for all instances of given class?
My solution is so far to create static methods for opening and closing, but i don't find it quite the right choice:
class Person {
protected static PreparedStatement stmt1;
protected static PreparedStatement stmt2;
protected static void initStatements(Connection conn) {
stmt1 = conn.PrepareStatement("select job_id from persons where person_id=:person_id");
stmt2 = conn.PrepareStatement("update persons set job_id=:job_id where person_id=:person_id");
}
protected static void closeStatements() {
stmt1.close();
stmt2.close();
}
public void increaseSalary() {
stmt1.execute(); // just a example
stmt2.execute();
}
}
void main {
// create prepared statements
Person.initStatements(conn);
// for each person, increase do some action which require sql connection
for (Person p : getAllPersons()) {
p.increaseSalary();
}
// close statements
Person.closeStatements();
}
Isn't there any other way how to use PreparedStatements inside multiple instances of class?