数据回滚
public class DataBaseTransaction {
Connection con = null;
public void testTransaction(){
try{
con.setAutoCommit(false);
Statement stmt = con.createStatement();
for(int i=0; i<2; i++)
stmt.execute("insert into user values(" + i + ",'ddd',24)");
System.out.println("before commit, the tables is :::::::");
viewTable();
con.commit();
System.out.println("after commit, the table is ::::::::");
viewTable();
} catch (Exception e) {
e.printStackTrace();
System.out.println("error");
try{
con.rollback();
}catch(SQLException se){
System.out.println("fatal error occur");
}
}
}
public void viewTable(){
try{
ResultSet rst = con.createStatement().executeQuery("select * from user");
while(rst.next()){
System.out.println(rst.getString("id"));
}
rst.close();
} catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
DataBaseTransaction test = new DataBaseTransaction();
test.con = java.sql.DriverManager.getConnection("jdbc:mysql://127.0.0.1/test","root","123456"); //跟据各人的数据而定
test.testTransaction();
}
}