今天在网上看到一篇博文,题目是:
4分钟插入1000万条数据到mysql数据库中
,以为颇有意思,就记录下来供本身学习。
MySQL版本:mysql-5.7.22-winx64
1,设置MySQL数据库表的容量
数据库表的默认容量是:4M,若是存储的数据超限的话会报错。
在windows控制台输入
mysql -uroot -p
,进入MySql数据库,输入
set global max_allowed_packet = 100*1024*1024;
注意后边的
分号。
2,主要代码
public static void main(String[] args) {
final String driver = "com.mysql.jdbc.Driver";
final String url = "jdbc:mysql://localhost:3306/project";
final String user = "root";
final String password = "253432";
Connection conn = null;
PreparedStatement pst = null;
long beginTime = 0;
long endTime = 0;
try {
Class.forName(driver);//指定链接类型
conn = DriverManager.getConnection(url, user, password);
if(conn != null) {
System.out.println("获取链接成功");
beginTime = new Date().getTime();//开始计时
String sqlPrefix = "insert into test (id,num) values ";
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// 比起st,pst会更好些
pst = (PreparedStatement) conn.prepareStatement("");//准备执行语句
// 外层循环,总提交事务次数
for (int i = 1; i <= 100; i++) {
suffix = new StringBuffer();
// 第j次提交步长
for (int j = 1; j <= 100000; j++) {
// 构建SQL后缀
suffix.append("('"+ UUID.randomUUID().toString()+"','"+i*j+"'"+"),");
}
// 构建完整SQL
String sql = sqlPrefix + suffix.substring(0, suffix.length() - 1);
// 添加执行SQL
pst.addBatch(sql);
// 执行操做
pst.executeBatch();
// 提交事务
conn.commit();
// 清空上一次添加的数据
suffix = new StringBuffer();
}
endTime = new Date().getTime();//开始计时
}else {
System.out.println("数据库链接失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("com.mysql.jdbc.Driver驱动类没有找到");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库地址错误");
}finally {//释放资源
System.out.println("插入成功,全部时间:"+ (endTime-beginTime));
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3,运行结果
能够看到用了两分钟
