package com.enhance.jdbc;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;
public class BatchTest {
private String driver;
private String url;
private String user;
private String pass;
private Connection conn;
private Statement stmt;
public void initParam(String paramFile) throws Exception{
Properties prop=new Properties();
prop.load(new FileInputStream(paramFile));
driver=prop.getProperty("driver");
url=prop.getProperty("url");
user=prop.getProperty("user");
pass=prop.getProperty("pass");
}
//只能执行 DDL 和 DML 不能执行 select
public void executeBatch(String[] sqls)throws Exception{
try{
Class.forName(driver);
conn=DriverManager.getConnection(url,user,pass);
//关闭自动提交 ,并开启事务
conn.setAutoCommit(false);
System.out.println("开启了事务!");
stmt=conn.createStatement();
for (String sql : sqls) {
stmt.addBatch(sql);
}
int[] nums=stmt.executeBatch(); //只能执行 DDL 和 DML 不能执行 select
for (int i = 0; i < nums.length; i++) {
System.out.println((i+1)+"行sql执行的结果:"+nums[i]);
}
conn.commit();
System.out.println("提交了事务!");
conn.setAutoCommit(true); //回复自动提交模式 ,主要在 线程池的时候 ,一定要复原后再放回去了,供其他 程序能正常使用 conn
}finally{
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
}
public static void main(String[] args) throws Exception {
BatchTest bt=new BatchTest();
bt.initParam("src/mysql.ini");
String[]sqls={
"insert into my_test values(null,'提交事务')"
,"insert into my_test values(null,'加油')"
,"update my_test set test_name='comme on!!' where test_id=4"
,"{call add_proc(4,5,null)}"};// 批量更新 不能执行 PreparedStatement 和 CallableStatement
bt.executeBatch(sqls);
}
}