Statement及PreparedStatement执行多个sql

本文介绍了Java JDBC中Statement与PreparedStatement的区别及应用场景。前者适用于执行不同SQL的批处理,但不支持预处理;后者则更适合执行相同的批处理,并提供预处理功能,性能更优。通过示例演示了如何使用两种方式执行批量SQL操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    这两个对象的区别:
1.Statement它更适合执行不同sql的批处理,它没有提供预处理功能,性能比较低。
2.PreparedStatement它适合执行相同的批处理,它提供了预处理功能,属性比较高。 
          /**
      * @param args
      * @throws SQLException
      * @throws ClassNotFoundException
      */
     public static void main(String[] args) throws ClassNotFoundException,
                SQLException {
            // 定义sql 语句
           String sql1 = "create table person(id int,name varchar(20))";
           String sql2 = "insert into person values(1,'tom')";
           String sql3 = "insert into person values(2,'fox')";
           String sql4 = "insert into person values(3,'tony')";
           String sql5 = "update person set name='张三' where id=1";
           String sql6 = "delete from person where id=3";
 
           Connection conn = jdbcUtils.getConnection();
           Statement st = conn.createStatement();
 
            // 添加批处理sql
           st.addBatch(sql1);
           st.addBatch(sql2);
           st.addBatch(sql3);
           st.addBatch(sql4);
           st.addBatch(sql5);
           st.addBatch(sql6);
 
            // 执行批处理sql
           st.executeBatch();
           st.clearBatch();
           st.close();
            conn.close();
 
     }
 
 
使用版本高一点的 jdbc的jar包时加入参数可开启缓存在url中加参数:
?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
     /**
      * @param args
      * @throws SQLException
      * @throws ClassNotFoundException
      */
     public static void main(String[] args) throws ClassNotFoundException,
                SQLException {
           String sqlString = "insert into person values(?,?)";
           Connection conn = jdbcUtils. getConnection();
           PreparedStatement pst = conn.prepareStatement(sqlString);
            long l = System. currentTimeMillis();
            for ( int i = 0; i < 10000; i++) {
                pst.setInt(1, i);
                pst.setString(2, "name" + i);
                pst.addBatch();
                 if (i % 1000 == 0) {
                     pst.executeBatch();
                     pst.clearBatch(); // 清空缓存
                }
           }
           pst.executeBatch();
           pst.close();
           conn.close();
           System. out.println(System. currentTimeMillis() - l);
     }

转载于:https://www.cnblogs.com/haofaner/p/5652750.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值