import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import com.xcliang.util.code.DBUtil;
public class deleteStudent {
//如果要想在一个持久层方法中书写多个相关的sql语句同时执行的话
//例:
public void deleteStudent(int studentID) {
//第一个sql语句
String sql1 = "update t_room set f_inNum = f_inNum - 1 where pk_roomid =(select fk_roomid from t_student where pk_studentid = "+studentID+")";
//第二个sql语句
String sql2 = "delete from t_student where pk_studentid = " + studentID;
//连接
Connection con = DBUtil.getConnection();
try {
//将sql语句的提交方式改为非自动提交
//注意:如果是true则表示自动提交第一个语句,第二个语句直接无视
con.setAutoCommit(false);
//多个sql语句执行
//第一句:
Statement stat1 = con.createStatement();
stat1.executeUpdate(sql1);
//第二句:
Statement stat2 = con.createStatement();
stat2.executeUpdate(sql2);
//提交sql语句执行
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
con.rollback();//如果两句sql语句中只要有一个语句出错,则回滚,都不执行
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
DBUtil.closeConnection(con);
}
}
}
import java.sql.SQLException;
import java.sql.Statement;
import com.xcliang.util.code.DBUtil;
public class deleteStudent {
//如果要想在一个持久层方法中书写多个相关的sql语句同时执行的话
//例:
public void deleteStudent(int studentID) {
//第一个sql语句
String sql1 = "update t_room set f_inNum = f_inNum - 1 where pk_roomid =(select fk_roomid from t_student where pk_studentid = "+studentID+")";
//第二个sql语句
String sql2 = "delete from t_student where pk_studentid = " + studentID;
//连接
Connection con = DBUtil.getConnection();
try {
//将sql语句的提交方式改为非自动提交
//注意:如果是true则表示自动提交第一个语句,第二个语句直接无视
con.setAutoCommit(false);
//多个sql语句执行
//第一句:
Statement stat1 = con.createStatement();
stat1.executeUpdate(sql1);
//第二句:
Statement stat2 = con.createStatement();
stat2.executeUpdate(sql2);
//提交sql语句执行
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
con.rollback();//如果两句sql语句中只要有一个语句出错,则回滚,都不执行
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
DBUtil.closeConnection(con);
}
}
}