CallableStatement執行存儲過程

 

/**
 * 使用CablleStatement調用存儲過程
 * @author APPle
 *
 */
public class Demo1 {

    /**
     * 調用帶有輸入參數的存儲過程
     * CALL pro_findById(4);
     */
    @Test
    public void test1(){
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        try {
            //獲取鏈接
            conn = JdbcUtil.getConnection();
            
            //準備sql
            String sql = "CALL pro_findById(?)"; //能夠執行預編譯的sql
            
            //預編譯
            stmt = conn.prepareCall(sql);
            
            //設置輸入參數
            stmt.setInt(1, 6);
            
            //發送參數
            rs = stmt.executeQuery(); //注意: 全部調用存儲過程的sql語句都是使用executeQuery方法執行!!!
            
            //遍歷結果
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt ,rs);
        }
    }
    
    /**
     * 執行帶有輸出參數的存儲過程
     * CALL pro_findById2(5,@NAME);
     */
    @Test
    public void test2(){
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        try {
            //獲取鏈接
            conn = JdbcUtil.getConnection();
            //準備sql
            String sql = "CALL pro_findById2(?,?)"; //第一個?是輸入參數,第二個?是輸出參數
            
            //預編譯
            stmt = conn.prepareCall(sql);
            
            //設置輸入參數
            stmt.setInt(1, 6);
            //設置輸出參數(註冊輸出參數)
            /**
             * 參數一: 參數位置
             * 參數二: 存儲過程當中的輸出參數的jdbc類型    VARCHAR(20)
             */
            stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
            
            //發送參數,執行
            stmt.executeQuery(); //結果不是返回到結果集中,而是返回到輸出參數中
            
            //獲得輸出參數的值
            /**
             * 索引值: 預編譯sql中的輸出參數的位置
             */
            String result = stmt.getString(2); //getXX方法專門用於獲取存儲過程當中的輸出參數
            
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt ,rs);
        }
    }
}
相關文章
相關標籤/搜索