批量添加数据简介

在JDBC中通过PreparedStatement的对象的addBatch()和executeBatch()方法进行数据的批量插入。

  • addBatch()把若干SQL语句装载到一起,然后一次性传送到数据库执行,即是批量处理sql数据的。
  • executeBatch()会将装载到一起的SQL语句执行。

注意:
MySql默认情况下是不开启批处理的。
数据库驱动从5.1.13开始添加了一个对rewriteBatchStatement的参数的处理,该参数能够让MySql开启批处理。在url中添加该参数:rewriteBatchedStatements=true

mysql的url参数

useUnicode [true | false] 是否使用编码集,需配合 characterEncoding 参数使用。
characterEncoding [utf-8 | gbk | …] 编码类型。
useSSL [true | false] 是否使用SSL协议。
rewriteBatchedStatements [true | false] 可以重写向数据库提交的SQL语句。

若有多个参数可&连接
如:?useSSL=false&charecterEncoding=true

  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. /**
  4. * 向mysql数据库批量添加数据
  5. */
  6. public class AddBatchTest {
  7. /**
  8. * 批量添加数据方式一(数据量小)
  9. */
  10. public void addBatch_1(){
  11. Connection connection = null;
  12. PreparedStatement preparedStatement = null;
  13. try {
  14. connection = JDBCUtils.getConnection();
  15. preparedStatement = connection.prepareStatement("insert into users values (default ,?,?)");
  16. //参数绑定
  17. for(int i=0;i<1000;i++){
  18. preparedStatement.setString(1,"laogeng"+i);
  19. preparedStatement.setInt(2,20);
  20. //缓存sql
  21. preparedStatement.addBatch();
  22. }
  23. preparedStatement.executeBatch();
  24. }catch (Exception e){
  25. e.printStackTrace();
  26. }finally {
  27. JDBCUtils.clossResource(preparedStatement,connection);
  28. }
  29. }
  30. /**
  31. * 批量添加数据方式二(数据量大)
  32. */
  33. public void addBatch_2(){
  34. Connection connection = null;
  35. PreparedStatement preparedStatement = null;
  36. try {
  37. connection = JDBCUtils.getConnection();
  38. preparedStatement = connection.prepareStatement("insert into users values (default ,?,?)");
  39. //参数绑定
  40. for(int i=0;i<1000;i++){
  41. preparedStatement.setString(1,"laogeng"+i);
  42. preparedStatement.setInt(2,20);
  43. //缓存sql
  44. preparedStatement.addBatch();
  45. if(i%500==0){
  46. preparedStatement.executeBatch();
  47. //清缓存
  48. preparedStatement.clearBatch();
  49. }
  50. }
  51. }catch (Exception e){
  52. e.printStackTrace();
  53. }finally {
  54. JDBCUtils.clossResource(preparedStatement,connection);
  55. }
  56. }
  57. public static void main(String[] args) {
  58. AddBatchTest addBatchTest = new AddBatchTest();
  59. addBatchTest.addBatch_2();
  60. }
  61. }