What is the method for batch submission in JDBC in Java…
In Java, batch processing with JDBC involves using the addBatch() and executeBatch() methods. Here is an example code:
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
// 开启批量提交模式
conn.setAutoCommit(false);
// 添加批量操作语句
stmt.addBatch("INSERT INTO table_name (column1, column2) VALUES (value1, value2)");
stmt.addBatch("UPDATE table_name SET column1 = value1 WHERE condition");
stmt.addBatch("DELETE FROM table_name WHERE condition");
// 执行批量操作
int[] result = stmt.executeBatch();
// 提交事务
conn.commit();
// 关闭连接
stmt.close();
conn.close();
} catch (SQLException e) {
// 处理异常
e.printStackTrace();
}
In the above code, the database connection object is first obtained using the getConnection() method, followed by creating a Statement object with the createStatement() method. The database connection is then set to manual commit mode by calling conn.setAutoCommit(false) method.
Next, use the addBatch() method to add the SQL statements that need to be executed to the batch operation. You can call the addBatch() method multiple times to add multiple operation statements.
Finally, the batch operation is executed by calling the executeBatch() method and the results are saved in an int array. Subsequently, the conn.commit() method is called to commit the transaction and save the batch operation results to the database.
Please be aware of the compatibility between the database driver and the database when using batch submissions. Some databases may not support batch submission operations, or may have limitations on specific types of operations (such as inserts and updates). Please refer to the documentation of the database driver for more information.