当前位置: 移动技术网 > IT编程>数据库>Mysql > 教你如何6秒钟往MySQL插入100万条数据的实现

教你如何6秒钟往MySQL插入100万条数据的实现

2020年08月29日  | 移动技术网IT编程  | 我要评论
一、思路往mysql中插入1000000条数据只花了6秒钟!关键点:1.使用preparedstatement对象2.rewritebatchedstatements=true 开启批量插入,插入只执

一、思路

往mysql中插入1000000条数据只花了6秒钟!

关键点:

1.使用preparedstatement对象


2.rewritebatchedstatements=true 开启批量插入,插入只执行一次,所有插入比较快。

二、 代码

package test0823.demo1;

import java.sql.*;

/**
 * @author : bei-zhen
 * @date : 2020-08-24 0:43
 */
public class jdbc2 {

  //static int count = 0;

  public static void main(string[] args) {

    long start = system.currenttimemillis();
    conn();
    long end = system.currenttimemillis();
    system.out.println("耗时:" + (end - start)/1000 + "秒");
  }

  public static void conn(){
    //1.导入驱动jar包
    //2.注册驱动(mysql5之后的驱动jar包可以省略注册驱动的步骤)
    //class.forname("com.mysql.jdbc.driver");
    //3.获取数据库连接对象
    connection conn = null;
    preparedstatement pstmt = null;
    {
      try {
        //"&rewritebatchedstatements=true",一次插入多条数据,只插入一次
        conn = drivermanager.getconnection("jdbc:mysql:///test?" + "&rewritebatchedstatements=true","root","root");
        //4.定义sql语句
        string sql = "insert into user values(default,?,?)";
        //5.获取执行sql的对象preparedstatement
        pstmt = conn.preparestatement(sql);
        //6.不断产生sql
        for (int i = 0; i < 1000000; i++) {
          pstmt.setstring(1,(int)(math.random()*1000000)+"");
          pstmt.setstring(2,(int)(math.random()*1000000)+"");
          pstmt.addbatch();
        }
        //7.往数据库插入一次数据
        pstmt.executebatch();
        system.out.println("添加1000000条信息成功!");

      } catch (sqlexception e) {
        e.printstacktrace();
      } finally {
        //8.释放资源
        //避免空指针异常
        if(pstmt != null) {
          try {
            pstmt.close();
          } catch (sqlexception e) {
            e.printstacktrace();
          }
        }

        if(conn != null) {
          try {
            conn.close();
          } catch (sqlexception e) {
            e.printstacktrace();
          }
        }
      }
    }

  }

}

三、运行结果

添加1000000条信息成功!
耗时:6秒


到此这篇关于教你如何6秒钟往mysql插入100万条数据的实现的文章就介绍到这了,更多相关mysql插入100万条数据内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网