07JDBC 사무 관리

1504 단어 자바
package cn.itcast.jdbc;
import cn.itcast.util.JDBCUtils;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;
/**
사무 조작
*/public class JDBCDemo10 {
public static void main(String[] args) {
    Connection conn = null;
    PreparedStatement pstmt1 = null;
    PreparedStatement pstmt2 = null;

    try {
        //1.    
        conn = JDBCUtils.getConnection();
        //    
        conn.setAutoCommit(false);

        //2.  sql
        //2.1    - 500
        String sql1 = "update account set balance = balance - ? where id = ?";
        //2.2    + 500
        String sql2 = "update account set balance = balance + ? where id = ?";
        //3.    sql  
        pstmt1 = conn.prepareStatement(sql1);
        pstmt2 = conn.prepareStatement(sql2);
        //4.     
        pstmt1.setDouble(1,500);
        pstmt1.setInt(2,1);

        pstmt2.setDouble(1,500);
        pstmt2.setInt(2,2);
        //5.  sql
        pstmt1.executeUpdate();
        //       
        int i = 3/0;

        pstmt2.executeUpdate();
        //    
        conn.commit();
    } catch (Exception e) {
        //    
        try {
            if(conn != null) {
                conn.rollback();
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }finally {
        JDBCUtils.close(pstmt1,conn);
        JDBCUtils.close(pstmt2,null);
    }


}

}

좋은 웹페이지 즐겨찾기