PreparedStatementバッチ処理とトランザクションコード
3778 ワード
PreparedStatement :
/*
* PreparedStatement:
1.addBatch() PreparedStatement
2.executeBatch() , , 。
*
*/
public class PreparedStatementCommitAndRollback {
public static void main(String args[]) {
Connection con = null;
PreparedStatement pstm = null;
try {
// 1.
con = JDBCUtil.getConnection();
// 2. sql
// 1). PreparedStatement ( slq ):
pstm = con.prepareStatement("insert into student values(?,?,?,?)");
con.setAutoCommit(false);//1, Auto commit false,
// 2) sql 1
pstm.setInt(1, 33);
pstm.setString(2,"wangqin");
pstm.setString(3, "c++");
pstm.setDouble(4, 78.5);
// 3) PreparedStatement 。
pstm.addBatch();
// 2) sql 2
pstm.setInt(1, 34);
pstm.setString(2,"wuytun");
pstm.setString(3, "c");
pstm.setDouble(4, 77);
// 3) PreparedStatement 。
pstm.addBatch();
// 2) sql 3
pstm.setInt(1, 31);
pstm.setString(2,"tetet");
pstm.setString(3, "c++");
pstm.setDouble(4, 90);
// 3) PreparedStatement 。
pstm.addBatch();
// 2) sql 4
pstm.setInt(1, 32);
pstm.setString(2,"liug");
pstm.setString(3, "c");
pstm.setDouble(4, 50);
// 3) PreparedStatement 。
pstm.addBatch();
// 4) , , 。
pstm.executeBatch();
System.out.println(" !");
// ,
con.commit();//2, (commit)
System.out.println(" !");
con.setAutoCommit(true);//3, Auto commit, true,
} catch (SQLException e) {
try {
// , ,
if(!con.isClosed()){
con.rollback();//4, catch SQLException , rollback( );
System.out.println(" , !");
con.setAutoCommit(true);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
JDBCUtil.closePreparedStatement(pstm);
JDBCUtil.closeConnection(con);
}
}
}
Statement , :
stm = con.createStatement();
con.setAutoCommit(false);
// , try , catch
stm.addBatch("insert into student values(23,'tangbao',' ',100)");
stm.addBatch("insert into student values(24,' ','c#',98)");
stm.addBatch("insert into student values(25,' ','java',90)");
stm.addBatch("insert into student values(26,' ',' ',89)");
stm.addBatch("insert into student values(27,'wqde','java',63)");
/*
* int[] executeBatch() throws
* SQLException , , 。
*/
stm.executeBatch();