如何使用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
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的如何使用JDBC调用存储在数据库中的函数或存储过程 */的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中array,arrayList
- 下一篇: Redis自定义动态字符串(sds)模块