温馨提示×

Java JDBC批量执行executeBatch方法怎么用

小亿
118
2024-03-02 09:13:01
栏目: 编程语言

JDBC中的executeBatch()方法用于批量执行SQL语句。下面是一个示例代码演示如何使用executeBatch()方法:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchExecutionExample {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 创建数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");

            // 创建预编译的SQL语句
            String sql = "INSERT INTO my_table (column1, column2) VALUES (?, ?)";
            preparedStatement = connection.prepareStatement(sql);

            // 设置批量执行的参数
            preparedStatement.setString(1, "value1");
            preparedStatement.setString(2, "value2");
            preparedStatement.addBatch();

            preparedStatement.setString(1, "value3");
            preparedStatement.setString(2, "value4");
            preparedStatement.addBatch();

            // 执行批量操作
            int[] result = preparedStatement.executeBatch();

            // 输出批量操作结果
            for (int i : result) {
                System.out.println("Number of rows affected: " + i);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

在这个示例中,我们首先创建数据库连接,然后创建一个预编译的SQL语句。接着设置批量执行的参数,调用addBatch()方法将每一组参数添加到批处理中。最后调用executeBatch()方法执行批处理操作,并获取执行结果。

0