通过命令行进行操作
开启事务: start transaction;
回滚 : rollback; --此次事务中所有的sql操作, 放弃.
提交 : commit; --此次事务中所有的sql操作, 作为一个整体, 提交.
通过Java进行操作
在java中,对数据库的操作默认是自动提交的。如果想开启一个事务,需要将自动提交关闭。
开启事务: conn.setAutoCommit(false);
回滚事务: conn.rollback();
提交事务: conn.commit();
public static void main(String[] args) throws Exception {
Connection conn = null;
PreparedStatement state = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8","root","");
conn.setAutoCommit(false);
state = conn.prepareStatement("update users set name =? where id=?");
state.setString(1,"123");
state.setString(2,"111");
state.executeUpdate();
state.setString(1,"qqq");
state.setString(2,"222");
state.executeUpdate();
conn.commit();
}catch(Exception e){
e.printStackTrace();
conn.rollback();
}finally{
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
try{
state.close();
}catch(Exception e){
e.printStackTrace();
}
}
}