Rya*_*ins 12 java sql-server stored-procedures jdbc return-value
我使用Microsoft SQL Server JDBC Driver 2.0通过Java连接到SQL Server(2005).
如何从存储过程中获取返回值?我做的事情如下:
Connection connection = dataSource.getConnection()
CallableStatement proc = connection.prepareCall("{ call dbo.mySproc() }");
proc.execute();
Run Code Online (Sandbox Code Playgroud)
我应该使用execute()吗?的executeQuery()?的executeUpdate()?这些似乎都没有默认返回值,但我不确定如何实现它.
编辑1:要清楚,我知道如何调用存储过程.这个问题具体是关于如何获得返回值(而不是结果集).返回值是一个整数,通常在执行没有结果集的查询时生成,或者您RETURN 0在SQL中特别声明了类似的内容.
编辑2:executeUpdate()返回一个int,但是这个int与返回值不同.此外,OUT参数与返回值不同.
Rya*_*ins 36
Bozho的第二个修订答案很接近,但并不完全存在.它确实引导我找到答案.
以我开始的代码示例为例,我们最终得到:
CallableStatement proc = connection.prepareCall("{ ? = call dbo.mySproc() }");
proc.registerOutParameter(1, Types.INTEGER);
proc.execute();
int returnValue = proc.getInt(1);
Run Code Online (Sandbox Code Playgroud)
这里的关键部分是prepareCall函数中"call"前面的"?=",它为返回值设置了一个位置registerOutputParameter.它必须注册为Integer,因为返回值始终是int(至少在SQL Server中,可能在其他DB中不同).因此,您必须使用它getInt.我测试了这种方法,它确实有效.