如何使用JDBC实现工具类抽取

2020-02-19 16:00:23刘景俊

2、批量插入数据

package com.rookie.bigdata;

import com.rookie.bigdata.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * CREATE TABLE `user` (
 * `USERNAME` varchar(30) DEFAULT NULL COMMENT '用户名',
 * `PASSWORD` varchar(10) DEFAULT NULL COMMENT '密码'
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 */
public class JDBCBatch {
  public static void main(String[] args) throws Exception {
    Connection connection = JDBCUtils.getConnection();
    //设置自动提交关闭
    connection.setAutoCommit(false);
    PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO USER VALUES (?,?)");

    for (int i = 1; i <= 5000; i++) {
      preparedStatement.setString(1, "张三" + i);
      preparedStatement.setString(2, "123" + i);
      preparedStatement.addBatch();
      if (i % 1000 == 0) {
        preparedStatement.executeUpdate();
        connection.commit();
        preparedStatement.clearBatch();
      }
    }
    preparedStatement.executeUpdate();
    connection.commit();
    preparedStatement.clearBatch();

  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。