java当中JDBC当中的transaction例子

7.jdbc的transaction例子:

import java.sql.*;

public class MySQlTransaction1 {

  public static void main(String[] args) throws SQLException {
/*in my sql: create table Accounts(
                ID int(4) not null,
                NAME varchar(15),
                BALANCE int(4),
                primary key(ID)
            )  type=INNODB;
  insert into Accounts values(1,'wangwu',100);
  insert into Accounts values(3,'zhangsan',300);
  insert into Accounts values(4,'lisi',400);
     */
    Connection con = null;
    Statement s = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
      //s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
/*by default, whenever execute a sql, it will commit automatically,
public void setAutoCommit(boolean autoCommit) throws SQLException
Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit 
mode, then all its SQL statements will be executed and committed as individual transactions. 
Otherwise, its SQL statements are grouped into transactions that are terminated by a call to
 either the method commit or the method rollback. By default, new connections are in
  auto-commit mode.        */

      s = con.createStatement();

      s.executeUpdate("update ACCOUNTS set BALANCE=508 where ID=3");
      System.out.println("333333");
/*下一步中本来应为where ID=4, 但是却误写成了www ID=4, 所以有错,所以到catch中,但rollback时
 , 却做不成功, 因为是autocommited模式,所以上一句ID=3,就做真改成508了。*/      
      s.executeUpdate("update ACCOUNTS set BALANCE=608 www ID=4");
      System.out.println("444444");

      System.out.println("con = " + con);
     }
    catch (Exception e) {
      try{
        con.rollback();
        System.out.println("rollback successfully");
      }catch (Exception ex)
      {
        ex.printStackTrace();
      }
    }
更多请见:http://www.mark-to-win.com/tutorial/java_10_jdbctransaction.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值