jdbc批量更新和批量插入数据如何编写
时间: 2024-12-18 21:34:11 浏览: 10
在JDBC中,批量更新和批量插入数据通常是为了提高性能和效率。这里有一个简单的示例说明如何操作:
**批量插入数据(BATCH INSERT)**:
```java
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement(Statement.RETURN_GENERATED_KEYS, Statement.BATCH); // RETURN_GENERATED_KEYS用于获取主键
// 批量插入数据
String sqlInsert = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement pstmtBatch = conn.prepareStatement(sqlInsert);
int count = 0;
for (Object[] data : dataList) { // dataList是一个包含待插入数据的数组
pstmtBatch.setInt(1, data[0]); // 将值设置到占位符
pstmtBatch.setString(2, data[1]);
pstmtBatch.addBatch(); // 添加到批处理
count++;
}
// 执行批处理
if (count > 0) {
int[] updateCounts = pstmtBatch.executeBatch(); // 返回每个语句的更新行数
for (int i = 0; i < updateCounts.length; i++) {
if (updateCounts[i] != 1) { // 遇到错误或不成功的插入
System.out.println("Error on insert: " + updateCounts[i]);
}
}
}
// 获取生成的主键
ResultSet generatedKeys = pstmtBatch.getGeneratedKeys();
while (generatedKeys.next()) {
long id = generatedKeys.getLong(1); // 如果表有唯一索引生成主键
// 处理主键
}
stmt.close();
conn.close();
```
**批量更新数据(BATCH UPDATE)**:
```java
Statement stmt = conn.createStatement(Statement.RETURN_UPDATES, Statement.BATCH);
String sqlUpdate = "UPDATE table_name SET column1 = ? WHERE column2 = ?";
PreparedStatement pstmtBatch = conn.prepareStatement(sqlUpdate);
for (Map.Entry<Long, String> entry : mapToUpdate.entrySet()) {
pstmtBatch.setLong(1, entry.getKey()); // 更新值
pstmtBatch.setString(2, entry.getValue());
pstmtBatch.addBatch();
}
// 执行批处理
int[] updateCounts = pstmtBatch.executeBatch();
for (int i = 0; i < updateCounts.length; i++) {
if (updateCounts[i] != 1) {
System.out.println("Error on update: " + updateCounts[i]);
}
}
stmt.close();
conn.close();
```
在上述代码中,务必检查`executeBatch()`返回的结果,以便处理可能出现的错误或未成功更新的情况。
阅读全文