mysql saveorupdate batch
To perform a batch saveOrUpdate operation in MySQL using JDBC, you can use the following steps:
-
Prepare your data: Create a list of objects that you want to save or update in the database.
-
Establish a database connection: Use JDBC to establish a connection with your MySQL database.
-
Disable auto-commit mode: Disable the auto-commit mode to ensure that changes are not committed immediately after each statement execution.
connection.setAutoCommit(false);
- Prepare the saveOrUpdate statement: Create a prepared statement with the SQL query for saveOrUpdate operation. The query should include placeholders for the values that will be inserted or updated.
String query = "INSERT INTO table_name(column1, column2) VALUES(?, ?) ON DUPLICATE KEY UPDATE column1 = VALUES(column1), column2 = VALUES(column2)";
PreparedStatement statement = connection.prepareStatement(query);
In this example, table_name is the name of your table, column1 and column2 are the column names that you want to save or update.
- Iterate through the list of objects: Iterate through the list of objects and set the values for each placeholder in the prepared statement.
for (YourObject object : objectsList) {
statement.setString(1, object.getValue1());
statement.setString(2, object.getValue2());
statement.addBatch(); // Add the statement to the batch
}
In this example, getValue1() and getValue2() are the methods to retrieve the values from your object.
- Execute the batch: Execute the batch of statements using the
executeBatch()method.
int[] batchResults = statement.executeBatch();
The executeBatch() method returns an array of integers representing the update counts for each statement in the batch.
- Commit the changes: After executing the batch, commit the changes to the database.
connection.commit();
- Close the resources: Close the prepared statement and the database connection.
statement.close();
connection.close();
Note: The "ON DUPLICATE KEY UPDATE" clause in the SQL query ensures that if a duplicate key violation occurs (e.g., unique constraint violation), the existing row will be updated instead of inserting a new row.
Make sure to handle any exceptions that may occur during the execution of these steps.
By following these steps, you can perform a batch saveOrUpdate operation in MySQL using JDBC
原文地址: https://www.cveoy.top/t/topic/hNRG 著作权归作者所有。请勿转载和采集!