public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 动态导入数据库的驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库链接
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/employee", "root", "wang314159");
// 开启事务
//不把其设置为true之前都是一个当作一个事务来处理
conn.setAutoCommit( false );
// 创造SQL语句
String sql = "INSERT INTO myrollback ( name,age,address,school ) VALUES ( 'test', 22,'大立即','hdu' )";
String sql2 = "INSERT INTO myrollback ( name,age,address,school ) VALUES ( 'test_Name', '33','大立即','hdu' ,'test')";
// 执行SQL语句
stmt = conn.createStatement();
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
// 提交事务
conn.commit();
System.out.println( "OK!" );
} catch (Exception e) {
e.printStackTrace();
System.out.println("有错误!");
try {
// 回滚事务
//撤销上面对事务的所有操作哈!
conn.rollback();
} catch ( Exception e2 ) {}
} finally {
// 关闭Statement
try {
stmt.close();
} catch (Exception e) {}
// 关闭Connection
try {
conn.close();
} catch (Exception e) {}
}
}
}
网友评论