使用 JDBC 在 MySQL 数据库中插入 5000 条记录需要花费太多时间



我正在使用jdbc,mysql-connector-java-8.0.20和xampp作为mysql服务器在数据库中插入5000条记录 我使用此链接来测试它,这是我测试的代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Random;
public class test {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sonoo", "root", "");
// here sonoo is database name, root is username and password
String sql = "insert into emp(name, age) values(?, ?)";
long startTime = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
PreparedStatement ps = con.prepareStatement(sql);
Random rnd = new Random();
int age = rnd.nextInt(60);
byte [] name = new byte[30];
rnd.nextBytes(name);
ps.setString(1, name.toString());
ps.setInt(2, age);
ps.executeUpdate();
System.out.println(i);
}
long endTime = System.currentTimeMillis();
System.out.println("taken time: " + (endTime - startTime));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

输出为:

所需时间: 315309

首先,也是最简单的,在循环之前准备一次PreparedStatement。喜欢

PreparedStatement ps = con.prepareStatement(sql);
for (int i = 0; i < 5000; i++) {
Random rnd = new Random();
int age = rnd.nextInt(60);
byte[] name = new byte[30];
rnd.nextBytes(name);
ps.setString(1, name.toString());
ps.setInt(2, age);
ps.executeUpdate();
System.out.println(i);
}

其次,如果这仍然不够快,请使用批处理。喜欢

PreparedStatement ps = con.prepareStatement(sql);
for (int i = 0; i < 5000; i++) {
Random rnd = new Random();
int age = rnd.nextInt(60);
byte[] name = new byte[30];
rnd.nextBytes(name);
ps.setString(1, name.toString());
ps.setInt(2, age);
ps.addBatch();
System.out.println(i);
}
ps.executeBatch();

顺便说一句,使用Arrays.toString(name);(您当前正在存储哈希代码(。

最新更新