`
cakin24
  • 浏览: 1328329 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Oracle在out参数中访问光标

阅读更多

一 概念

申明包结构
包头:负责申明
包体:负责实现
 
二 需求
查询某个部门中所有员工的所有信息
 
三 包头
  1. CREATE OR REPLACE
  2. PACKAGE MYPACKAGE AS
  3. type empcursor isref cursor;
  4. procedure queryEmplist(dno in number,emplist out empcursor);
  5. END MYPACKAGE;
 
四 包体
包体需要实现包头中声明的所有方法
  1. CREATE OR REPLACE
  2. PACKAGE BODY MYPACKAGE AS
  3. procedure queryEmplist(dno in number,emplist out empcursor) AS
  4. BEGIN
  5. --打开光标
  6. open emplist forselect*from emp where deptno = dno;
  7. END queryEmplist;
  8. END MYPACKAGE;
五 在应用程序中访问包中的存储过程
1、代码
  1. package demo.oracle;
  2. import java.sql.CallableStatement;
  3. import java.sql.Connection;
  4. import java.sql.ResultSet;
  5. import oracle.jdbc.OracleCallableStatement;
  6. import oracle.jdbc.OracleTypes;
  7. import org.junit.Test;
  8. import demo.utils.JDBCUtils;
  9. publicclassTestCursor{
  10. /*
  11. CREATE OR REPLACE PACKAGE MYPACKAGE AS
  12. type empcursor is ref cursor;
  13. procedure queryEmplist(dno in number,emplist out empcursor);
  14. END MYPACKAGE;
  15. * */
  16. @Test
  17. publicvoid testCursor(){
  18. String sql="{call MYPACKAGE.queryEmplist(?,?)}";
  19. Connection conn =null;
  20. CallableStatement call =null;
  21. ResultSet rs =null;
  22. try{
  23. //获取数据库的连接
  24. conn =JDBCUtils.getConnection();
  25. //创建statement
  26. call = conn.prepareCall(sql);
  27. //对于in参数,赋值
  28. call.setInt(1,10);
  29. //对于out参数,申明
  30. call.registerOutParameter(2,OracleTypes.CURSOR);
  31. //执行调用
  32. call.execute();
  33. //取出该部门中所有员工的信息
  34. rs =((OracleCallableStatement)call).getCursor(2);
  35. while(rs.next()){
  36. //取出该员工的员工号,姓名,薪水和职位
  37. int empno = rs.getInt("empno");
  38. String name =rs.getString("ename");
  39. double salay = rs.getDouble("sal");
  40. String job = rs.getString("empjob");
  41. System.out.println(empno+"\t"+name+"\t"+salay+"\t"+job);
  42. }
  43. }catch(Exception e){
  44. e.printStackTrace();
  45. }finally{
  46. JDBCUtils.release(conn, call, rs);
  47. }
  48. }
  49. }
2、运行结果
7782    CLARK    6450.0    MANAGER
7839    KING    10100.0    PRESIDENT
7934    MILLER    3300.0    CLERK
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics