JDBC调用存储过程
步骤:
1:通过Connection 对象的prepareCall()方法创建一个CallableStatement对象的实例,
在使用Connection对象的prepareCall()方法时,需要传入一个String类型的字符串,
该方法指明如何调用存储过程。
{?= call
[(
,
, ...)]}
{call
[(
,
, ...)]}
2:通过CallableStatement对象的registerOutParameter()方法注册out参数;
3:通过CallableStatement对象的SetXXX()方法设定IN或IN OUT参数;
若想将参数设置为null 可以使用setNull()方法
4:通过CallableStatement的excute()方法执行存储过程;
5:如果调用的是带返回参数的存储过程,还需要通过CallableStatement对象的getXxx()获取其返回值;
案例代码:
?
/*
* 文件名:FunctionTest.java
* 版权:Copyright by www.huawei.com
* 描述:
* 修改人:Cuigaochong
* 修改时间:2015-8-28
* 跟踪单号:
* 修改单号:
* 修改内容:
*/
package com.jdbc.function;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Test;
import com.jdbc.cgc.pro.OracleDbUtils;
/**
* <一句话功能简述> <功能详细描述>
*
* @author 姓名 工号
* @version [版本号, 2015-8-28]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class FunctionTest
{
private OracleDbUtils utils = OracleDbUtils.getInstance();
/**
* <一句话功能简述>JDBC调用存储函数 <功能详细描述>
*
* @see [类、类#方法、类#成员]
*/
@Test
public void test00()
{
Connection conn = null;
CallableStatement callableStatement = null;
String sql = "{?=call get_sall(?,?)}";
try
{
conn = utils.connection();
// 1:通过Connection 对象的prepareCall()方法创建一个CallableStatement对象的实例,
// 在使用Connection对象的prepareCall()方法时,需要传入一个String类型的字符串,
// 该方法指明如何调用存储过程。
// {?= call
[(
,
, ...)]} // {call
[(
,
, ...)]} callableStatement = conn.prepareCall(sql); // 2:通过CallableStatement对象的registerOutParameter()方法注册out参数; callableStatement.registerOutParameter(1, Types.NUMERIC); callableStatement.registerOutParameter(3, Types.NUMERIC); // 3:通过CallableStatement对象的SetXXX()方法设定IN或IN OUT参数; // 若想将参数设置为null 可以使用setNull()方法 callableStatement.setInt(2, 80); // 4:通过CallableStatement的excute()方法执行存储过程; callableStatement.execute(); // 5:如果调用的是带返回参数的存储过程,还需要通过CallableStatement对象的getXxx()获取其返回值; double sum = callableStatement.getDouble(1); long empCount = callableStatement.getLong(3); System.out.println(sum); System.out.println(empCount); } catch (SQLException e) { e.printStackTrace(); } finally { utils.releaseSource(callableStatement, conn, null); } } }
|