我正在使用 postgresql 并创建了一些存储过程。现在我想通过 jdbc 访问存储过程并处理结果。存储过程的结果是整数或 TABLE。
我发现了以下内容:
CallableStatement upperProc = conn.prepareCall("{ ? = call upper( ? ) }");
upperProc.registerOutParameter(1, Types.VARCHAR);
upperProc.setString(2, "lowercase to uppercase");
upperProc.execute();
String upperCased = upperProc.getString(1);
upperProc.close();
有了这个,我想我可以处理单个整数返回,但我如何处理 TABLE 返回?
最佳答案
您需要做的是注册您想要使用的所有返回变量。在提供的代码中,您只注册了第一个输出参数。
像这样注册前 3 个:
String callableSQL = "{call upper(?)}";
try {
dbConnection = getDBConnection();
callableStatement = dbConnection.prepareCall(callableSQL);
callableStatement.setString(1, "lowercase to uppercase");
//register multiple output parameters to match all return values
callableStatement.registerOutParameter(1, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.XYZ); //any data type here
callableStatement.execute();
//do something with your return values
String xyz = callableStatement.getString(1);
//... for other items you have registered.
} catch (SQLException up) {
throw up; //haha!
} finally {
//Silently close off
if (callableStatement != null) {
callableStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
另见
关于java - 如何用JDBC调用PostgreSQL存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110185/