1.自己总结的,很简单的Java事物 ---个人笔记记录.
/**
* 学生批量转班
* @param inv
* @return
* @throws Exception
*/
@Get("studentClassTransfer")
public String studentClassTransfer(Invocation inv, @Param("check_list") List<Integer> check_list, @Param("pid") int pid, @Param("gid") int gid,
@Param("cid") int cid) throws Exception {
Date d = new Date();
// 查询当前学生是那个阶段,年级,班级的,如何和要转的一样就不转了
if (check_list.size() > 0) {
for (int i = 0; i < check_list.size(); i++) {
StudentClassInfo stuClass = classInfoDAO.getCidToUid(check_list.get(i));
if (stuClass != null) {
// 根据班级级id查出年级id
ClassInfo classInfo = classInfoDAO.getGidToCid(stuClass.getCid());
if (classInfo != null) {
// 根据年级id查出学段id
GradeInfo gradeInfo = gradeInfoDAO.getGrade(classInfo.getGid());
if (gradeInfo != null) {
if (gradeInfo.getPid() == pid && classInfo.getGid() == gid && stuClass.getCid() == cid) {
// 要转的和本用户一样就不转了
}
else {
// 加入事物
// 1.先删除当前用户原在班级(uid)classInfoDAO.delStudentClass();
// 2.在新班级里添加一条记录classInfoDAO.insertStudentClass()
StudentManageController s = new StudentManageController();
String sqlDel = "update t_student_class set flag = 1 where uid = " + check_list.get(i) + "";
String sqlIns = "insert into t_student_class(uid,cid,inserttime) values(" + check_list.get(i) + "," + cid + "," + d.getTime()
+ ")";
String sqlAll[] = { sqlDel, sqlIns };
StartTransaction(s.getConnection(), sqlAll);
}
}
}
}
}
}
return "@<script>location.href='lookStudentInfo'</script>";
}
/**
* 链接数据库 获取Connection
* @return
*/
public Connection getConnection() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://*************/fyzxx?useUnicode=true&characterEncoding=utf8";
String user = "****";
String password = "******";
Connection conn = null;
try {
Class.forName(driver);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/**
* 事物处理
* @param con
* @param sqls
* @throws Exception
*/
public void StartTransaction(Connection con, String[] sqls) throws Exception {
if (sqls == null) {
return;
}
Statement sm = null;
try {
// 事务开始
System.out.println("事务处理开始!");
con.setAutoCommit(false); // 设置连接不自动提交,即用该连接进行的操作都不更新到数据库
sm = con.createStatement(); // 创建Statement对象
// 依次执行传入的SQL语句
for (int i = 0; i < sqls.length; i++) {
sm.execute(sqls[i]);// 执行添加事物的语句
}
System.out.println("提交事务处理!");
con.commit(); // 提交给数据库处理
System.out.println("事务处理结束!");
// 事务结束
// 捕获执行SQL语句组中的异常
}
catch (SQLException e) {
try {
System.out.println("事务执行失败,进行回滚!\n");
con.rollback(); // 若前面某条语句出现异常时,进行回滚,取消前面执行的所有操作
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
finally {
sm.close();
}
}