MySQL Java: 使用PreparedStatement批量插入多行数据
在Java应用程序中,经常需要将多行数据插入到MySQL数据库中。使用JDBC API可以完成这个任务,但要注意效率问题。因此,可以使用PreparedStatement来批量执行插入操作。本篇文章将介绍在Java应用程序中使用PreparedStatement批量插入多行数据的方法。
阅读更多:MySQL 教程
1. 创建PreparedStatement对象
在调用PreparedStatement的批量方法之前,需要创建PreparedStatement对象。示例代码如下:
String sql = "INSERT INTO table_name (col1, col2) VALUES (?, ?);";
PreparedStatement statement = connection.prepareStatement(sql);
其中,connection
是连接到MySQL数据库的Connection对象,sql
是需要执行的SQL语句,其中包含两个占位符?
。
2. 执行批量插入操作
创建PreparedStatement对象之后,就可以执行批量插入操作了。使用PreparedStatement的addBatch方法将多个插入操作进行缓存,然后通过executeBatch方法一次性提交到数据库。示例代码如下:
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.addBatch();
statement.setString(1, "value3");
statement.setString(2, "value4");
statement.addBatch();
int[] result = statement.executeBatch();
上面的代码中,我们先通过setString方法设置每个占位符的值,然后使用addBatch方法缓存插入操作。最后,执行executeBatch方法来一次性提交所有缓存的操作。executeBatch方法会返回一个int数组,其中包含每个操作的返回结果。如果返回值为0,则表示操作成功。
3. 关闭PreparedStatement对象
批量插入操作完成后,需要关闭PreparedStatement对象。示例代码如下:
statement.close();
4. 完整示例代码
下面是使用PreparedStatement批量插入多行数据的完整示例代码。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertMultipleRows {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, user, password);
String sql = "INSERT INTO table_name (col1, col2) VALUES (?, ?);";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.addBatch();
statement.setString(1, "value3");
statement.setString(2, "value4");
statement.addBatch();
int[] result = statement.executeBatch();
statement.close();
connection.close();
}
}
总结
本篇文章介绍了在Java应用程序中使用PreparedStatement批量插入多行数据的方法,包括创建PreparedStatement对象、执行批量插入操作以及关闭PreparedStatement对象。使用PreparedStatement批量插入数据可以大大提高效率,特别是在需要插入大量数据时。