java执行sql语句块,如何从java执行多个SQL语句

本文探讨了在Java中执行多条SQL语句的问题。用户希望一次执行多个动态查询,却无法实现。解决方案是使用addBatch和executeBatch命令进行批量处理,可将相关SQL语句分组提交,减少通信开销、提升性能,还给出了判断数据库是否支持该特性的方法及示例代码。

I want to execute the multiple queries or job in one execute.

Something like this

eg:

String query="select * from tab1;insert into tab1 values(...);update tab1..;delete from tab1...;"

Statement st = con1.createStatement();

ResultSet rs = st.executeQuery(query);

Or multiple select queries.Queries will be dynamic.

But I am not able to do this.What is the way to run multiple queries separated by semi colon.

解决方案

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.

The

The

Just as you can add statements to a batch for processing, you can remove them with the

EXAMPLE:

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());

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值