java执行多条sql语句

Java中,可以使用JDBC的Statement或PreparedStatement对象来执行多条SQL语句。首先建立数据库连接,然后创建Statement或PreparedStatement对象,最后调用executeUpdate()方法执行SQL语句。

Java中,我们可以使用JDBC(Java Database Connectivity)来批量执行SQL语句,以下是一个简单的示例,展示了如何使用PreparedStatement和addBatch()方法来批量执行SQL语句。

1、导入所需的库

java执行多条sql语句

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

2、加载数据库驱动

public static void loadDriver() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

3、建立数据库连接

java执行多条sql语句

public static Connection getConnection() {
    String url = "jdbc:mysql://localhost:3306/test";
    String username = "root";
    String password = "123456";
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}

4、批量执行SQL语句

public static void executeBatch(Connection connection) {
    String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
    try {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < 10; i++) {
            preparedStatement.setString(1, "User" + i);
            preparedStatement.setInt(2, 20 + i);
            preparedStatement.addBatch();
        }
        int[] result = preparedStatement.executeBatch();
        System.out.println("批量插入成功,影响行数:" + result.length);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

5、主函数调用

java执行多条sql语句

public static void main(String[] args) {
    loadDriver();
    Connection connection = getConnection();
    executeBatch(connection);
}

这个示例中,我们首先导入了所需的库,然后加载了数据库驱动并建立了数据库连接,接着,我们定义了一个批量执行SQL语句的方法,该方法使用PreparedStatement和addBatch()方法来批量插入数据,在主函数中调用这些方法来执行批量插入操作。

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/642591.html

(0)
未希新媒体运营
上一篇 2024-05-21 15:29
下一篇 2024-05-21 15:30

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入