JDBC的批处理

    xiaoxiao2025-02-28  54

    批处理

     

    1 Statement批处理

    批处理就是一批一批的处理,而不是一个一个的处理!

    当你有10条SQL语句要执行时,一次向服务器发送一条SQL语句,这么做效率上很差!处理的方案是使用批处理,即一次向服务器发送多条SQL语句,然后由服务器一次性处理。

    批处理只针对更新(增、删、改)语句,批处理没有查询什么事儿!

     

    可以多次调用Statement类的addBatch(String sql)方法,把需要执行的所有SQL语句添加到一个“批”中,然后调用Statement类的executeBatch()方法来执行当前“批”中的语句。

    void addBatch(String sql):添加一条语句到“批”中;int[] executeBatch():执行“批”中所有语句。返回值表示每条语句所影响的行数据;void clearBatch():清空“批”中的所有语句。

     

               for(int i = 0; i < 10; i++) {

                  String number = "S_10" + i;

                  String name = "stu" + i;

                  int age = 20 + i;

                  String gender = i % 2 == 0 ? "male" : "female";

                  String sql = "insert into stu values('" + number + "', '" + name + "', " + age + ", '" + gender + "')";

                  stmt.addBatch(sql);

               }

               stmt.executeBatch();

     

    当执行了“批”之后,“批”中的SQL语句就会被清空!也就是说,连续两次调用executeBatch()相当于调用一次!因为第二次调用时,“批”中已经没有SQL语句了。

    还可以在执行“批”之前,调用Statement的clearBatch()方法来清空“批”!

     

    2 PreparedStatement批处理

    PreparedStatement的批处理有所不同,因为每个PreparedStatement对象都绑定一条SQL模板。所以向PreparedStatement中添加的不是SQL语句,而是给“?”赋值。

               con = JdbcUtils.getConnection();

               String sql = "insert into stu values(?,?,?,?)";

               pstmt = con.prepareStatement(sql);

               for(int i = 0; i < 10; i++) {

                  pstmt.setString(1, "S_10" + i);

                  pstmt.setString(2, "stu" + i);

                  pstmt.setInt(3, 20 + i);

                  pstmt.setString(4, i % 2 == 0 ? "male" : "female");

                  pstmt.addBatch();

               }

               pstmt.executeBatch();

          3.打开批处理

    driverClassName=com.mysql.jdbc.Driver

    url=jdbc:mysql://localhost:3306/mydb3?rewriteBatchedStatements=true

    username=root

    password=123

     

    最新回复(0)