欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

JDBC使用事务实例

程序员文章站 2022-05-12 08:17:22
...

package qddx .JDBC ; import java .sql .* ; public class useTransaction { public static void main(String[] args) { // TODO Auto-generated method stub Connection conn = null ; Statement st = null ; PreparedStatement pst = null ; ResultSet rs

package qddx.JDBC;
import java.sql.*;
public class useTransaction {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Connection conn = null;
        Statement st = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        Savepoint sp = null;
        try{
        conn = JDBC_Connection.getConnection();
        //指定事务隔离级别
        conn.setTransactionIsolation(conn.TRANSACTION_READ_UNCOMMITTED);
        pst = conn.prepareStatement("create table users (id smallint,username text)");
        pst.execute();
        //提交事务
        conn.commit();
        pst.close();
        }catch(SQLException e){
            System.err.println("连接数据库或者建表失败");
            System.err.println("事务回滚到回滚点");
            try{
            conn.rollback();
            }catch(SQLException ex){
                //ex.printStackTrace();
                System.out.println("回滚失败");
            }
            try{
            conn.setSavepoint();//设置一个存储点
            st = conn.createStatement();
            st.executeUpdate("insert into users values(110,'Janes')");//执行更新语句
            //st.executeUpdate("insert into users values('shibai','Janes')");//执行更新语句 失败的例子
            conn.commit();//提交事务
            conn.releaseSavepoint(sp);//释放存储点
            st.close();
            conn.close();

            }catch(SQLException et){
                System.err.println("操作失败");
                System.err.println("事务回滚到存储点");
                try{
                conn.rollback(sp);
                st.close();
                conn.close();
                }catch(SQLException exc){
                    System.out.println("回滚到存储点失败");
                    //exc.printStackTrace();;
                }
                //et.printStackTrace();
            }
            //e.printStackTrace();
        }

    }

}