當我想將它用於給定類的所有實例時,將PreparedStatement初始化放到什麼位置最好?JDBC PreparedStatements vs Objects - 初始化的位置
我的解決方案是迄今爲止創造的開啓和關閉的靜態方法,但我不覺得很正確的選擇:
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();
}
是不是有任何其他方式如何使用內部多用預處理類的實例?
感謝,因爲這只是一個小程序,我把我所有的數據庫請求爲普通DAO對象,這是我進入域邏輯類(例如人)。 – Franto