JDBC使用事務實例

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();
        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章