import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class BatchInsertExample {
public static void main(String[] args) {
List<Student> studentList = List.of(
new Student(1, "Alice", 20),
new Student(2, "Bob", 21)
);
String url = "jdbc:mysql://localhost:3306/yourdatabase";
String username = "yourusername";
String password = "yourpassword";
String insertQuery = "INSERT INTO students (id, name, age) VALUES (?,?,?)";
try (Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
for (Student student : studentList) {
preparedStatement.setInt(1, student.getId());
preparedStatement.setString(2, student.getName());
preparedStatement.setInt(3, student.getAge());
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
System.out.println("Batch insertion successful.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 数据库连接:使用
DriverManager.getConnection(url, username, password)
获取数据库连接。
- 预编译语句:使用
connection.prepareStatement(insertQuery)
创建预编译语句,用于批量插入数据。
- 添加批处理:通过循环遍历学生对象列表,为预编译语句设置参数,并使用
preparedStatement.addBatch()
将参数添加到批处理中。
- 执行批处理:调用
preparedStatement.executeBatch()
执行批处理操作,将数据批量插入数据库。
- 异常处理与资源关闭:使用
try-with-resources
语句确保在操作完成后自动关闭数据库连接和预编译语句,同时捕获SQLException
并进行相应处理。