如何使用JDBC调用存储在数据库中的函数或存储过程 */

//创建存储过程

alter proc [dbo].[proc_get_customer1] (
@sid varchar(10),
@name varchar(20) out,
@birth datetime out,
@email varchar(30) out,
@id char(10) out
)with recompile
as
begin
select id,name,birth,email from customers where id<@sid
select @id=id,@name=name,@birth=birth,@email=email from customers where id<@sid
end

/**
*
* @param sql
* @param outCount
* @param params:为IN参数即输入参数,需要注意的是存储过程或函数的输入参数在前,输出参数在后,若有output即输入输出参数的话将output属性的参数放到中间
*/
public void callableProc(String sql, int outCount, Object... params) {
Connection connection = null;
CallableStatement callableStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCTools.getConnection();
callableStatement = connection.prepareCall(sql);
if (!sql.contains("=")) {
for (int i = 0; i < params.length; i++) {
callableStatement.setObject(i + 1, params[i]);
}
callableStatement.registerOutParameter(2,Types.VARCHAR);
callableStatement.registerOutParameter(3, Types.DATE);
callableStatement.registerOutParameter(4, Types.VARCHAR);
callableStatement.registerOutParameter(5,Types.CHAR);
}else{
for (int i = 0; i < params.length; i++) {
callableStatement.setObject(i + 2, params[i]);
}
}
resultSet=callableStatement.executeQuery();
//获得输出参数的cstmt.getInt(3)必须在处理完结果集的所有内容后再执行否则会抛出异常:java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Object has been closed.
while(resultSet.next()){
for(int i=0;i<4;i++){
System.out.print(resultSet.getObject(i+1)+" a ");
}
System.out.println();
}
System.out.println(callableStatement.getString(2));
System.out.println(callableStatement.getDate(3));
System.out.println(callableStatement.getString(4));
System.out.println(callableStatement.getString(5));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCTools.release(resultSet, callableStatement, connection);
}

}

 

//下面是测试

@Test
public void testCustomerProc() {
String sql = "{call proc_get_customer1(?,?,?,?,?)}";
String[] params = { "100090" };
customerDao.callableProc(sql, 5, params);
}

转载于:https://www.cnblogs.com/xiaona19841010/p/5226181.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值