JDBC 添加一万条数据,要求保证效率,请写出代码
时间: 2023-07-16 13:16:38 浏览: 112
以下是一个简单的示例代码,可以批量插入一万条数据:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcBatchInsert {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
int batchSize = 1000; // 每次批量插入的记录数
long startTime = System.currentTimeMillis();
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 关闭自动提交事务
conn.setAutoCommit(false);
// 创建预编译的 SQL 语句
ps = conn.prepareStatement("INSERT INTO student(id, name, age) VALUES (?, ?, ?)");
// 循环插入记录
for (int i = 1; i <= 10000; i++) {
ps.setInt(1, i);
ps.setString(2, "student" + i);
ps.setInt(3, 18);
ps.addBatch(); // 添加到批处理中
if (i % batchSize == 0) {
ps.executeBatch(); // 批量执行插入操作
conn.commit(); // 提交事务
ps.clearBatch(); // 清空批处理
}
}
// 处理剩余未达到批量大小的记录
ps.executeBatch();
conn.commit();
long endTime = System.currentTimeMillis();
System.out.println("插入一万条记录共耗时:" + (endTime - startTime) + "ms");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
try {
conn.rollback(); // 发生异常时回滚事务
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
try {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码使用了批量插入的方式,每次插入1000条记录,共执行10次插入操作,可以有效提高插入效率。同时,关闭自动提交事务和使用预编译的 SQL 语句也可以提高效率。需要注意的是,在插入过程中发生异常时,需要回滚事务,确保数据的一致性。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)