【发布时间】:2020-12-18 02:11:39
【问题描述】:
JDBC 具有将多个查询组合在一个单元中并在一次网络访问中将其传递到数据库的特性。
如本代码示例所示:
String[] EMPLOYEES = new String[]{"Zuck","Mike","Larry","Musk","Steve"};
String[] DESIGNATIONS = new String[]{"CFO","CSO","CTO","CEO","CMO"};
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?)";
PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL);
for(int i = 0; i < EMPLOYEES.length; i++){
String employeeId = UUID.randomUUID().toString();
employeeStmt.setString(1,employeeId);
employeeStmt.setString(2,EMPLOYEES[i]);
employeeStmt.setString(3,DESIGNATIONS[i]);
employeeStmt.addBatch();
}
employeeStmt.executeBatch();
但是,对于 SQL,我们具有使用带有许多 VALUES 组的 INSERT 的功能,就像在:
String[] EMPLOYEES = new String[] {"Zuck","Mike","Larry","Musk","Steve"};
String[] DESIGNATIONS = new String[] {"CFO","CSO","CTO","CEO","CMO"};
StringBuilder insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?)"
+ ", (?, ?, ?)".repeat(EMPLOYEES.length - 1);
PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL.toString());
int columnIndex = 0;
for(int i = 0; i < EMPLOYEES.length; i++){
String employeeId = UUID.randomUUID().toString();
employeeStmt.setString(++columnIndex, employeeId);
employeeStmt.setString(++columnIndex, EMPLOYEES[i]);
employeeStmt.setString(++columnIndex, DESIGNATIONS[i]);
}
employeeStmt.execute();
我需要知道的是,这两种方法有什么区别?
观察:
第一个例子来自https://www.baeldung.com/jdbc-batch-processing,第二个例子是我编辑的。 英语不是我的母语,这是我的第一篇文章,非常抱歉。
【问题讨论】: