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();

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

  • 相关阅读:
    进程间通迅之消息队列
    进程间通讯之共享内存
    标准块CP功能实现
    标准字符cp功能
    文件cp功能
    jest 的 coverage 提示 unknown 的解决方案
    js中的相等
    getBoundingClientRect 和 requestAnimFrame 的polyfill
    设计模式(4): 给组件实现单独的store
    Vue项目移动端滚动穿透问题
  • 原文地址:https://www.cnblogs.com/rrttp/p/8012863.html
Copyright © 2011-2022 走看看