使用 CallableStatement 接口调用存储过程

一、CallableStatement 接口

CallableStatement 主要是调用数据库中的存储过程,CallableStatement 也是 Statement 接口的子接口。在使用 CallableStatement 时可以接收存储过程的返回值。

void registerOutParameter(int parameterIndex, int sqlType)

按顺序位置 parameterIndex 将 OUT 参数注册为 JDBC 类型 sqlType。

 1 /**
 2      * 调用存储过程,通过id查询bookName
 3      * @param id
 4      * @return
 5      * @throws Exception
 6      */
 7     private static String getBookNameById(int id)throws Exception {
 8         Connection con=dbUtil.getCon();//获取数据库连接
 9         String sql="{CALL pro_getBookNameById(?,?)}";
10         CallableStatement cstmt=con.prepareCall(sql);
11         cstmt.setInt(1, id);//设置第一个参数
12         cstmt.registerOutParameter(2, Types.VARCHAR);//设置返回类型
13         cstmt.execute();
14         //bN为返回值名称
15         String bookName=cstmt.getString("bN");//获取返回值
16         dbUtil.close(cstmt, con);
17         return bookName;
18         
19     }
20     
21     public static void main(String[] args) throws Exception {
22         System.out.println("图书名称是:"+getBookNameById(8));
23     }
原文地址:https://www.cnblogs.com/xiaoyqng/p/8321138.html