360SDN.COM

首页/Java/列表

Java的jdbc使用addBatch进行批处理操作的几种方式

来源:  2014-03-27 12:57:05    评论:0点击:

SQL批处理是JDBC性能优化的重要武器,经本人研究总结,批处理的用法有三种。

方式一、批量执行预定义模式的SQL

public static void exeBatch(Connection conn) { 
  try { 
          String sql = "insert into t_example (code, name) values (?,?)";
          PreparedStatement pstmt = conn.prepareStatement(sql);
          pstmt.setString(1, "java2");
          pstmt.setString(2, "java");
          //添加一次预定义参数
          pstmt.addBatch();       
          pstmt.setString(1, "360sdn");
          pstmt.setString(2, "软件开发技术网");
          //再添加一次预定义参数
          pstmt.addBatch();       
          //批量执行预定义SQL
          pstmt.executeBatch();
    } catch (SQLException e) {
          e.printStackTrace();
    } finally {
          closeConnection(conn);
  }
 } 

方式二、批量执行混合模式的SQL、有预定义的,还有静态的

//批量执行混合模式的SQL、有预定义的,还有静态的
public static void exeBatchMixedSQL( Connection conn) { 
  PreparedStatement pstmt =null;
 try { 
         String sql = "insert into t_example (code, name) values (?,?)";
         PreparedStatement pstmt = conn.prepareStatement(sql);
         pstmt.setString(1, "java");
         pstmt.setString(2, "360sdn");
 //添加一次预定义参数
         pstmt.addBatch();   
          pstmt.setString(1, "360sdn");
          pstmt.setString(2, "软件开发技术网");
//再添加一次预定义参数
         pstmt.addBatch();    
         //添加一次静态SQL
         pstmt.addBatch("update t_example set code= '360.com' where code='360sdn'");
         //批量执行预定义SQL
         pstmt.executeBatch();
 } catch (SQLException e) {
         e.printStackTrace();
 } finally {
         closeConnection(conn);
 }
        }

方式三、执行批量静态的SQL

//执行批量静态的SQL
ublic static void exeBatchSQL(Connection conn) { 
  try { 
          Statement stmt = conn.createStatement();
          //连续添加多条静态SQL
          stmt.addBatch("insert into t_example (code, name) values ('java', '360sdn.com')");
          stmt.addBatch("insert into t_example (code, name) values ('360', '360sdn')");
          stmt.addBatch("delete from t_example where code='java'");
          stmt.addBatch("update t_example set kind = '360data' where kind='360'");
//批量执行不支持Select语句
//          stmt.addBatch("select count(*) from t_example");  
          //执行批量执行
          stmt.executeBatch();
  } catch (SQLException e) {
          e.printStackTrace();
  } finally {
          closeConnection(conn);
  }
        } 
为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权