目录
在Java中实现插入几十万条数据,有多种方法可以使用。以下是其中的几种:
1,使用批量插入
使用批量插入可以有效地提高插入速度。下面是一个示例代码:
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
conn.setAutoCommit(false);
String sql = "INSERT INTO mytable (name, age, email) VALUES (?, ?, ?)";
ps = conn.prepareStatement(sql);
for (int i = 0; i < data.size(); i++) {
ps.setString(1, data.get(i).getName());
ps.setInt(2, data.get(i).getAge());
ps.setString(3, data.get(i).getEmail());
ps.addBatch();
if ((i + 1) % 1000 == 0) { // 每1000条数据执行一次批量插入
ps.executeBatch();
conn.commit();
}
}
ps.executeBatch();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2,使用多线程
使用多线程可以将数据分为多个部分并行插入,提高效率。以下是一个示例代码
final int THREAD_COUNT = 10; // 线程数
final int BATCH_SIZE = data.size() / THREAD_COUNT; // 每个线程处理的数据量
ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
for (int i = 0; i < THREAD_COUNT; i++) {
final int startIndex = i * BATCH_SIZE;
final int endIndex = (i + 1) * BATCH_SIZE;
executor.submit(new Runnable() {
public void run() {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
conn.setAutoCommit(false);
String sql = "INSERT INTO mytable (name, age, email) VALUES (?, ?, ?)";
ps = conn.prepareStatement(sql);
for (int j = startIndex; j < endIndex; j++) {
ps.setString(1, data.get(j).getName());
ps.setInt(2, data.get(j).getAge());
ps.setString(3, data.get(j).getEmail());
ps.executeUpdate();
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
});
}
executor.shutdown();
while (!executor.isTerminated()) {} // 等待所有线程完成任务
3,使用存储过程
使用存储过程可以将多个SQL操作合并为一个操作,减少通信开销。以下是一个示例代码:
Connection conn = null;
CallableStatement cs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
String sql = "{CALL insert_data(?, ?, ?)}"; // 存储过程
cs = conn.prepareCall(sql);
for (int i = 0; i < data.size(); i++) {
cs.setString(1, data.get(i).getName());
cs.setInt(2, data.get(i).getAge());
cs.setString(3, data.get(i).getEmail());
cs.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (cs != null) {
try {
cs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
版权声明:本文为weixin_46504244原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。