2011-09-23 63 views
0

當我想將它用於給定類的所有實例時,將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(); 
} 

是不是有任何其他方式如何使用內部多用預處理類的實例?

回答

2

人會是你的域邏輯類嗎?然後我建議不要將數據訪問方法和PreparedStatement放在那裏,而是放在一個單獨的數據訪問對象中。

DAO方法是否會異步調用,例如在Web應用程序中?然後,我建議不要在這些調用之間重複使用PreparedStatements或Connections。對於連接,我會使用連接池。 更多關於重用預處理語句: Reusing a PreparedStatement multiple times

+0

感謝,因爲這只是一個小程序,我把我所有的數據庫請求爲普通DAO對象,這是我進入域邏輯類(例如人)。 – Franto

0

通常最好是使用ConnectionSurvivalPack並給這對每個人都參與:

Class SurvivalPack { 
    private Connection connection; 
    private PreparedStatement st1; 
    // add constructor and appropriate getter/setter 
    // getter for PreparedStatements could create statements on demand 
    void close(){ 
     st1.close(); 
     con.close(); 
    } 
} 

void main(...){ 
    SurvivalPack survivalPack = new SurvivalPack(conn); 
    for(Person p: getAllPersons()){ 
     p.increaseSalary(survivalPack); 
    } 
    survivalPack.close(); 
} 

優點:

  • 多線程是沒有問題的,因爲資源沒有線程之間共享。
  • 所有數據庫資源捆綁在一個地方。這使資源管理更容易和更一致。
  • 跟着代碼的流程要容易得多,因爲沒有來自半全局變量的副作用可能發生。