1. 数据库环境
1.1 MySQL版本
我用到的是MySQL5.6.38版本。
1.2 数据表创建
CREATE TABLE `student
` (
`id
` char(32) NOT NULL,
`t_name
` varchar(255) DEFAULT NULL,
`t_password
` varchar(255) DEFAULT NULL,
`sex
` char(2) DEFAULT NULL,
`description
` varchar(255) DEFAULT NULL,
`pic_url
` varchar(255) DEFAULT NULL,
`school_name
` varchar(255) DEFAULT NULL,
`regist_date
` datetime DEFAULT NULL,
`remark
` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id
`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
;
1.3 更改MySQL数据库max_allowed_packet属性大小
max_allowed_packet属性用于限制Server接受的数据包大小。有时候大的插入和更新会受 max_allowed_packet 参数限制,导致写入或者更新失败。
查看默认的max_allowed_packet大小(默认大小只有4M或1M,由版本决定):
show VARIABLES
like '%max_allowed_packet%'
修改max_allowed_packet大小:
set global max_allowed_packet
= 100*1024*1024;
修改参数大小后,一定要重新登录,才能看到属性值的改变。
2. 大数据量的生产
package _13数据库超大数据量生成
;
import java
.sql
.Connection
;
import java
.sql
.DriverManager
;
import java
.sql
.PreparedStatement
;
import java
.sql
.SQLException
;
import java
.util
.Date
;
import java
.util
.UUID
;
public class InsertTest {
private static final String URL
= "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8";
private static final String DRIVER
= "com.mysql.jdbc.Driver";
private static final String USERNAME
= "root";
private static final String PASSWORD
= "sss";
public static void main(String
[] args
) throws SQLException
, ClassNotFoundException
{
Class
.forName(DRIVER
);
Connection conn
= DriverManager
.getConnection(URL
, USERNAME
, PASSWORD
);
if (conn
!= null
) {
System
.out
.println("获取连接成功");
insert(conn
);
} else {
System
.out
.println("获取连接失败");
}
}
public static void insert(Connection conn
) {
Long begin
= new Date().getTime();
String prefix
= "INSERT INTO student (id,t_name,t_password,sex,description,pic_url,school_name,regist_date,remark) VALUES ";
try {
StringBuffer suffix
= new StringBuffer();
conn
.setAutoCommit(false);
PreparedStatement pst
= (PreparedStatement
) conn
.prepareStatement(" ");
for (int i
= 1; i
<= 10; i
++) {
suffix
= new StringBuffer();
for (int j
= 1; j
<= 100000; j
++) {
String id
= UUID
.randomUUID().toString().replaceAll("-","");
suffix
.append("('" + id
+ "','" + i
* j
+ "','123456'" + ",'男'" + ",'教师'" + ",'www.bbk.com'" + ",'XX大学'" + ",'" + "2016-08-12 14:43:26" + "','备注'" + "),");
}
String sql
= prefix
+ suffix
.substring(0, suffix
.length() - 1);
pst
.addBatch(sql
);
pst
.executeBatch();
conn
.commit();
suffix
= new StringBuffer();
}
pst
.close();
conn
.close();
} catch (SQLException e
) {
e
.printStackTrace();
}
Long end
= new Date().getTime();
System
.out
.println("1000万条数据插入花费时间 : " + (end
- begin
) / 1000 + " s");
System
.out
.println("插入完成");
}
}
参考文章:https://www.cnblogs.com/fanwencong/p/5765136.html