java之JDBC多條語句執行


在開發過程中,有時我們需要執行多條SQL語句,那如何處理才能解決這樣的問題?

 

1,多條語句執行錯誤

原因:試圖用一個PreparedStatement對象,執行多次SQL操作。程序會提示一下錯誤:

Operation not allowed after ResultSet closed

因為在執行while(rs.next())時 , rs已經關閉。

while(rs.next())

當再用 PreparedStatement statement = con.prepareStatement(sql1) 建立查詢時會提示上面的錯誤。

 

解決上面多次操作的問題:

1,每一條sql語句建立一個 PreparedStatement 對象,每個PreparedStatement 對象操作一條sql語句,這對程序性能影響不大,因為JDBC性能消耗主要是在連接數據庫上。

如:

            pstat = con.prepareStatement("update userr set money=money-? where name=?");             pstat.setInt(1, 100);             pstat.setString(2, "李四");             pstat.executeUpdate();             pstat = con.prepareStatement("update userr set money=money+? where name=?");             pstat.setInt(1, 200);             pstat.setString(2, "張三");             pstat.executeUpdate();                        pstat = con.prepareStatement("update temp set count=count+? where name=?");             pstat.setInt(1, 1);             pstat.setString(2, "張三");             pstat.executeUpdate();             con.commit();

 

2,Mysql批處理,這樣只需創建一個PreparedStatement對象,就能操作多條sql語句。

PreparedStatement  ps=conn.createStatement(); ps.addBatch("update user set money=money-100 where name='張三'"); ps.addBatch("update user set money=money+100 where name='李四'"); ps.addBatch("update temp set count=count+1 where name='張三'"); ps.executeBatch();

 

小弟作為初學者,若文中存在不足之處,歡迎批評指正!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM