我有一个存储过程" test",看起来像:
CREATE PROCEDURE test
@name varchar(32)
AS
DECLARE
@login_status TINYINT,
@syb_login varchar(20),
@syb_pass varchar(20)
...
..
BEGIN
SELECT @status = 0
SELECT @login as login,
@pass as pass,
@status as status
RETURN 0
END
我需要传递一个输入参数" myName"作为此过程的输入参数,然后返回登录,传递和状态作为输出(仅来自一个记录)参数。
在JDBC中,我试着这样做:
String query = "{call test(?,?,?)}";
System.out.println(query);
CallableStatement proc = null;
ResultSet rs;
try {
proc = connection.prepareCall(query);
proc.setString(1, "myName");
proc.registerOutParameter(2, java.sql.Types.VARCHAR);
proc.registerOutParameter(3, java.sql.Types.VARCHAR);
proc.execute();
System.out.println(proc.getString(2));
这总是例外:
java.sql.SQLException: JZ0SG: A CallableStatement did not return as many output parameters as the application had registered for it.
at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(Unknown Source)
at com.sybase.jdbc4.jdbc.SybStatement.handleSQLE(Unknown Source)
at com.sybase.jdbc4.jdbc.ParamManager.nextResult(Unknown Source)
at com.sybase.jdbc4.jdbc.ParamManager.doGetOutValueAt(Unknown Source)
at com.sybase.jdbc4.jdbc.ParamManager.getOutValueAt(Unknown Source)
at com.sybase.jdbc4.jdbc.SybCallableStatement.getString(Unknown Source)
我尝试了JDBC execute SQL Server stored procedure with return value and input/output parameters, https://msdn.microsoft.com/en-us/library/ms378108.aspx但这没有用。
答案 0 :(得分:5)
有两种方法:
<强> 1。重新定义您的程序(推荐)
创建存储过程时必须声明输出参数:
CREATE PROCEDURE test
@name varchar(32),
@login varchar(32) = null output,
@pass varchar(32) = null output,
@status int = -1 output
AS
BEGIN
SET @status = 0
SELECT @login = logincolumn,
@pass = passcolumn
FROM usertable
END
然后您可以将它与JDBC一起使用,如下所示:
String query = "{call test(?,?,?,?)}";
[...]
proc = connection.prepareCall(query);
proc.setString(1, "myName");
proc.registerOutParameter(2, java.sql.Types.VARCHAR);
proc.registerOutParameter(3, java.sql.Types.VARCHAR);
proc.registerOutParameter(4, java.sql.Types.INTEGER);
注意:
set
或select
进入已声明的变量才能为其提供输出
值。 <强> 2。从多个结果集中捕获结果(不推荐)
Connection con;
CallableStatement proc = null;
ResultSet rs;
String qry = "{call test(?)}";
proc = con.prepareCall(qry);
proc.setString(1, "name");
proc.executeQuery();
// first result set returning the status
rs = proc.getResultSet();
if (rs.next()) {
System.out.println(rs.getString(1));
}
// second result set returning login and pass
if (proc.getMoreResults()) {
rs = proc.getResultSet();
if (rs.next()) {
System.out.println(rs.getString("login"));
System.out.println(rs.getString("pass"));
}
}