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