关于JDBC的批处理,这是JDBC2.0以后兴起的概念。所谓批处理就是可以一次性执行多条SQL命令,比如:插入、删除等。如果想要实现批处理操作,则需要使用PreparedStatement的addBatch()方法将一条SQL语句添加到批处理中,接着使用executeBatch()方法来执行前面添加的全部命令。示例代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
package javase.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCBatchDemo {
public static void main(String[] args) {
String sql = "INSERT INTO users(username,password,classId) VALUES(?,?,?)";
Connection connection = JDBCConnection.getConnection();
try {
PreparedStatement pStatement = connection.prepareStatement(sql);
for (int i = 0; i < 10; i++) {
pStatement.setString(1, "测试-" + i);
pStatement.setString(2, "root-" + i);
pStatement.setInt(3, i);
pStatement.addBatch(); // 将一条数据加入到批处理中等待一起执行
}
int result[] = pStatement.executeBatch(); // 批量执行
System.out.println("插入了 " + result.length + " 条数据");
pStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
效果如下:
输出:
|
1
|
插入了 10 条数据 |
本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1762435,如需转载请自行联系原作者