zoukankan      html  css  js  c++  java
  • 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();

    小弟作为初学者,若文中存在不足之处,欢迎批评指正!

  • 相关阅读:
    MJExtension的使用
    Swift
    2月22号 UITableView
    1月25号 CALayer
    1月22号 animation—1
    1月22号 KVC KVO
    2016.01.22 简单动画
    2016.01.22 KVC&KVO
    2016.01.22 单例模式(Singleton)
    2016.01.21 UITabBarController
  • 原文地址:https://www.cnblogs.com/rrttp/p/8012863.html
Copyright © 2011-2022 走看看