首次发帖,只为记录本菜鸟的学习历程,不一定非常到位,so...仅限参考。
代码贴上:
public static void main(String args[]){
Connection conn=null;
Statement stmt = null ;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1/table?user=user&password=password";
conn = DriverManager.getConnection(url);
if(!conn.isClosed())
System.out.println("数据库连接成功!");
conn.setAutoCommit(false);//关闭自动提交事务
String sql1 ="insert into table(id,name) values('1','李大呆')";
String sql2 ="insert into table(id,name) values('2','王小帅')";
stmt = conn.createStatement();
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
conn.commit(); //手动提交
}catch(Exception e){
e.printStackTrace();
try {
System.out.println("回滾....");
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
到这里,一次简单的操作mysql 事务处理就算完成了。
特別提醒:mysql建表时,默认的存储引擎是:MyISAM ,需要改為:InnoDB ,不然事务不会回滚。