zoukankan      html  css  js  c++  java
  • 使用Batch批量添加数据

    package com.atguigu.jdbc;

    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.PreparedStatement;
    import java.sql.Statement;

    import org.junit.Test;

    public class JDBCTest {
    @Test
    public void testBatch(){
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    try{
    connection=JDBCTools.getConnection();
    JDBCTools.beginTx(connection);
    String sql="insert into customers values(?,?,?)";
    preparedStatement=connection.prepareStatement(sql);
    long beginTime=System.currentTimeMillis();
    for(int i=0;i<100000;i++){

    preparedStatement.setInt(1,i+100001);
    preparedStatement.setString(2, "");
    preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
    //preparedStatement.executeUpdate();
    //积攒SQL
    preparedStatement.addBatch();
    //当积攒到一定程度,就统一的执行一次,并且清空先前积攒的SQL
    if((i+1)%300==0){
    preparedStatement.executeBatch();
    preparedStatement.clearBatch();
    }
    }
    //若总条数不是批量数值的整数倍,则还需要再额外执行一次
    if((100000%300)!=0){
    preparedStatement.executeBatch();
    preparedStatement.clearBatch();
    }
    long stopTime=System.currentTimeMillis();
    JDBCTools.commit(connection);
    System.out.println(beginTime-stopTime);
    }catch(Exception e){
    e.printStackTrace();
    JDBCTools.rollback(connection);
    }finally{
    JDBCTools.release(null, preparedStatement, connection);
    }
    }

    @Test
    public void testBatchWithPreparedStatement(){
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    try{
    connection=JDBCTools.getConnection();
    JDBCTools.beginTx(connection);
    String sql="insert into customers values(?,?,?)";
    preparedStatement=connection.prepareStatement(sql);
    long beginTime=System.currentTimeMillis();
    for(int i=0;i<100000;i++){

    preparedStatement.setInt(1,i+100001);
    preparedStatement.setString(2, "");
    preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
    preparedStatement.executeUpdate();
    }
    long stopTime=System.currentTimeMillis();

    JDBCTools.commit(connection);
    System.out.println(beginTime-stopTime);
    }catch(Exception e){
    e.printStackTrace();
    JDBCTools.rollback(connection);
    }finally{
    JDBCTools.release(null, preparedStatement, connection);
    }
    }

    }

  • 相关阅读:
    webview学习
    Android中webview html5 自动播放本地视频
    Android中使用WebView实现全屏切换播放网页视频
    Android中实现Activity的透明背景效果
    App过大
    Android 9.0网络权限适配
    Android中自定义环形图2
    Android中自定义环形图
    Android中自定义水球
    vue学习指南:第五篇(详细)
  • 原文地址:https://www.cnblogs.com/xiaona19841010/p/5204359.html
Copyright © 2011-2022 走看看