java批量执行查询sql语句_如何从Java执行多个SQL语句

小编典典

您可以使用以下示例实现addBatch和executeBatch命令同时执行多个 SQL 命令。

批处理允许您将相关的SQL语句分组为一个批处理,并通过一次调用将其提交给数据库。参考

当您一次将多个SQL语句发送到数据库时,可以减少通信开销,从而提高性能。

不需要JDBC驱动程序即可支持此功能。您应该使用该DatabaseMetaData.supportsBatchUpdates()方法确定目标数据库是否支持批量更新处理。如果您的JDBC驱动程序支持此功能,则该方法返回true。

Statement,PreparedStatement和CallableStatement 的 executeBatch()用于启动所有组合在一起的语句的执行。

正如您可以将语句添加到批处理中一样,您可以使用 addBatch()方法添加的所有语句。但是,您不能有选择地选择要删除的语句。

例:

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","name","pass");

Statement stmt = con.createStatement

(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

String insertEmp1 = "insert into emp values

(10,'jay','trainee')";

String insertEmp2 = "insert into emp values

(11,'jayes','trainee')";

String insertEmp3 = "insert into emp values

(12,'shail','trainee')";

con.setAutoCommit(false);

stmt.addBatch(insertEmp1);//inserting Query in stmt

stmt.addBatch(insertEmp2);

stmt.addBatch(insertEmp3);

ResultSet rs = stmt.executeQuery("select * from emp");

rs.last();

System.out.println("rows before batch execution= "

+ rs.getRow());

stmt.executeBatch();

con.commit();

System.out.println("Batch executed");

rs = stmt.executeQuery("select * from emp");

rs.last();

System.out.println("rows after batch execution= "

+ rs.getRow());

}

}

2020-09-08

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值