3分钟左右的时间如何向MySQL数据库中插入100万条数据

一、编写测试案例向MySQL数据库中插入百万条数据。测试数据表建表脚本如下:

use db_xk;

drop table if exists tb_test2;

create table tb_test2 (

        id int primary key auto_increment,

        subject varchar(50) not null,

        description varchar(200) not null,

        teacher_id int(10) zerofill not null,

        student_id int(10) zerofill default null,

        state boolean not null default false

);

       测试案例源码如下:

package test;

 

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.SQLException;

 

import util.DBUtil;

 

public class TestDataBase2 {

 

    public static void main(String[] args) {

 

       Connection conn = DBUtil.getConnection();

       String sql = "insert into tb_test2(subject, description, teacher_id, student_id) values (?,?,?,?)";

 

       try {

           PreparedStatement prep = conn.prepareStatement(sql);

          

           // 将连接的自动提交关闭,数据在传送到数据库的过程中相当耗时

           conn.setAutoCommit(false);

           long start = System.currentTimeMillis();

          

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

             

              long start2 = System.currentTimeMillis();

             

              // 一次性执行插入10万条数据

              for (int j = 0; j < 100000; j++) {

                 

                  prep.setString(1, "test2");

                  prep.setString(2, "test3");

                  prep.setInt(3, 1234562);

                  prep.setInt(4, 12354545);

                 

                  // 将预处理添加到批中

                  prep.addBatch();

                 

              }

             

              // 预处理批量执行

              prep.executeBatch();

              prep.clearBatch();

              conn.commit();

             

              long end2 = System.currentTimeMillis();

             

              // 批量执行一次批量打印执行依次的时间

              System.out.print("inner"+i+": ");

              System.out.println(end2 - start2);

 

           }

          

           long end = System.currentTimeMillis();

           System.out.print("total: ");

           System.out.println(end - start);

          

       } catch (SQLException e) {

 

           e.printStackTrace();

       } finally {

 

           DBUtil.close(conn);

       }

      

    }

 

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值