Java Statement一次执行多条sql语句

网上的代码基本上没有问题,不过会存在一点瑕疵没有说清楚,导致试验了很久才成功,现在总结需要如下:

1.我们看了statement的execute文档,是可以进行多个语句执行的,文档内容如下:

在这里插入图片描述

2.除了执行execute方法之外,我们还需要在连接jdbc的时候增加allowMultiQueries=true的属性

3.代码如下:

public class Test {
    public static void main(String[] args){
        try {
            test1();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void test1() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool?characterEncoding=utf-8&allowMultiQueries=true", "root", "1234");
        Statement statement = conn.createStatement();
        String no = "abc';select * from student where '1' = '1";
        String sql = "select * from student where studentno = '"+no+"'";
        boolean b = statement.execute(sql);
        while(true){
            if(b){
                System.out.println("第一句");
            }else{
                if(statement.getUpdateCount() != -1){
                    System.out.println("第二局");
                }else{
                    break;
                }
            }
            b = statement.getMoreResults();
        }
        conn.close();
    }
}



  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中,可以使用 JDBC(Java Database Connectivity)来执行多条 SQL 语句。下面是一个简单的示例代码,展示如何一次执行多条 SQL 语句: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class MultipleSQLExecutionExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, username, password)) { Statement statement = conn.createStatement(); String sql1 = "INSERT INTO users (id, name) VALUES (1, 'John')"; String sql2 = "UPDATE users SET name = 'Jane' WHERE id = 1"; statement.addBatch(sql1); statement.addBatch(sql2); int[] result = statement.executeBatch(); System.out.println("Number of rows affected by each statement:"); for (int i : result) { System.out.println(i); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 在上述示例中,我们使用 `createStatement()` 创建一个 `Statement` 对象来执行 SQL 语句。然后,我们使用 `addBatch()` 将多条 SQL 语句添加到批处理中。最后,我们使用 `executeBatch()` 执行批处理,并获取每个语句影响的行数。 请注意,这只是一个简单的示例,实际应用中可能需要更复杂的逻辑处理和错误处理。此外,具体的实现方式可能会因数据库类型和驱动程序的不同而有所差异。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值