26、Java调用Oracle存储过程?

来源:互联网 发布:c语言 字符串统计函数 编辑:程序博客网 时间:2024/06/05 07:58

①导包

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;

②声明对象

// 声明数据库连接对象
        Connection con = null;

// 定义标准形式调用已储存过程CallableStatement对象
        CallableStatement cs = null;     

 // 定义结果集ResultSet的对象rs
        ResultSet rs = null;

③调用存储过程取结果集

try {
            // 获取连接
            con = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
            // 调用存储过程
            cs = con.prepareCall("{存储过程名称(?,?,?,?,?)}");
            // 设置输入参数
            cs.setString(1, xxx);
            // 设置输入参数
            cs.setString(2, yyy);
            // 设置输出参数
            cs.registerOutParameter(3, OracleTypes.NUMBER);
            cs.registerOutParameter(4, OracleTypes.VARCHAR);
            cs.registerOutParameter(5, OracleTypes.CURSOR);
            cs.execute();
            // 获取结果集
            rs = (ResultSet) cs.getObject(5);

④遍历结果集,构建实体bean

            /*
             * ResultSet rsRbb游标(指针)最初位于第一行之前
             * 调用next()方法游标(指针)往下移动一行
             * 新的当前行有效,则返回 true;如果不存在下一行,则返回 false
             */

         Bean bean;

          while(rs.next()){

                 bean = new Bean();

                 bean.setxx(rs.getString("XXX"));

         }

} catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rsRbb != null) {
                try {
                    // 关闭结果集rsRbb,释放资源
                    rsRbb.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (cs != null) {
                try {
                    // 关闭CallableStatement对象,释放资源
                    cs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            try {
                // 关闭连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

//释放资源,关闭连接  注意try catch finlly 语句。




           

0 0
原创粉丝点击