package org.zp.preparedStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.zp.util.DbUtil;
public class shiwu{
public static void main(String[] args){
String sql = "delete from T_Student where stu_id=?";
String sql1 = "delete from T_Score where stu_id=?";
Connection conn = DbUtil.getConnection();
PreparedStatement pstmt = null;
try {
conn.setAutoCommit(false);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 9);
pstmt.executeUpdate();
pstmt = conn.prepareStatement(sql1);
pstmt.setInt(1, 9);
pstmt.executeUpdate();
conn.commit();//提交事务
System.out.println("事务已提交,删除成功!");
} catch (SQLException e) {
System.err.print("执行出错,事务回滚!");//只要有一条语句执行不成功就会回滚。
System.err.print(e.getMessage());
try {
conn.rollback();
} catch (SQLException e1) {
System.err.print("事务回滚失败!");
e1.printStackTrace();
}
}finally {
DbUtil.close(null);
}
}
}