批量往mysql里面插入1000万条数据_教你如何6秒钟往MySQL插入100万条数据的实现

教你如何6秒钟往MySQL插入100万条数据的实现,数据,对象,站长站,文章,相关文章

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

易采站长站,站长之家为您整理了教你如何6秒钟往MySQL插入100万条数据的实现的相关内容。

一、思路

往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万条数据内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!以上就是关于对教你如何6秒钟往MySQL插入100万条数据的实现的详细介绍。欢迎大家对教你如何6秒钟往MySQL插入100万条数据的实现内容提出宝贵意见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值