注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 Exchange服务器系列课程之..
 帮助

JDBC事务的操作


2008-03-17 22:44:02
 标签:JDBC 操作 事务   [推送到技术圈]

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://sophi.blog.51cto.com/340461/66326
import java.sql.*;

public class TestTransaction {

    public static void main(String[] args) {
  Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null;
  try{
      Class.forName("com.mysql.jdbc.Driver");
      String url = "jdbc:mysql://localhost:3306/test?user=root&password=11111111";
      conn = DriverManager.getConnection(url);
      stmt = conn.createStatement();
      //将自动提交事务设置为false
      conn.setAutoCommit(false);
      stmt.addBatch("update person set name = 'maomaocong' where id = 6");
      stmt.addBatch("insert into person values(5 ,'huixianmaomao')");
      stmt.addBatch("delete from person where id = 5");
      stmt.executeBatch();
      //提交事务以后要恢复事务的自动提交状态
      conn.commit();
      conn.setAutoCommit(true);
      rs = stmt.executeQuery("select * from person");
      while(rs.next()){
    System.out.print(rs.getString(1));
    System.out.println(rs.getString(2));
      }
  } catch(ClassNotFoundException e){
      e.printStackTrace();
  } catch(SQLException e){
      e.printStackTrace();
      try{
    if(conn != null){
        conn.rollback();
        conn.setAutoCommit(true);
        System.out.println("rollback OK!");
    }
      } catch (SQLException e1){
    e1.printStackTrace();
      }
  } finally {
      try{
    if(rs != null){
        rs.close();
        rs = null;
    }
    if(stmt != null){
        stmt.close();
        stmt = null;
    }
    if(conn != null){
        conn.close();
        conn = null;
    }
      } catch (SQLException e){
    e.printStackTrace();
      }
  }
    }
}

本文出自 ““技”忆” 博客,请务必保留此出处http://sophi.blog.51cto.com/340461/66326





    文章评论
 
2008-03-18 10:16:49
最好多些文字的说明 那就好了

2008-08-02 10:34:22
JDBC还可以设置事物的类型、不单单是要么提交、要么回滚吧!还有食物类型的。

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: