从JDBC MSSQL获取返回值

编程入门 行业动态 更新时间:2024-10-24 23:16:00
本文介绍了从JDBC MSSQL获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用Microsoft SQL Server JDBC Driver 2.0通过Java连接到SQL Server(2005)。

I'm connecting to SQL Server (2005) through Java using the Microsoft SQL Server JDBC Driver 2.0.

如何从存储过程中获取返回值?我正在做类似的事情:

How do I get the return value from a stored procedure? I'm doing something like:

Connection connection = dataSource.getConnection() CallableStatement proc = connection.prepareCall("{ call dbo.mySproc() }"); proc.execute();

我应该使用execute()吗?的executeQuery()?的executeUpdate()?这些似乎都没有默认返回值,但我不确定如何达到它。

Should I be using execute()? executeQuery()? executeUpdate()? None of these seem to return a return value by default but I'm not really sure how to get to it.

编辑1:要清楚,我知道如何调用存储过程。这个问题具体是关于如何获得返回值(而不是结果集)。返回值是一个整数,通常在您执行没有结果集的查询时生成,或者您在SQL中特别声明了类似 RETURN 0 的内容。

EDIT 1: To be clear, I know how to call stored procedures. This question is specifically about how to get the RETURN VALUE (as opposed to a Result Set). The Return Value is an integer that is usually generated when you execute a query with no Result Set or if you specifically state something like RETURN 0 in your SQL.

编辑2:executeUpdate()返回一个int,但是这个int与返回值不同。此外,OUT参数与返回值不同。

EDIT 2: executeUpdate() returns an int but this int is not the same as the Return Value. Also, an OUT parameter is not the same as a return value.

推荐答案

Bozho的第二个修订答案很接近,但并不完全存在。它确实引导我找到答案。

Bozho's 2nd revised answer was close but not quite there. It did lead me to the answer though.

以我开始的代码为例,我们最终得到:

Taking the code example I started with we end up with:

CallableStatement proc = connection.prepareCall("{ ? = call dbo.mySproc() }"); proc.registerOutParameter(1, Types.INTEGER); proc.execute(); int returnValue = proc.getInt(1);

这里的关键部分是 prepareCall 为返回值设置位置的函数和 registerOutputParameter 。它必须注册为Integer,因为返回值始终是int(至少在SQL Server中,可能在其他DB中不同)。因此,您必须使用 getInt 来获取它。我测试了这种方法,它确实有效。

The key pieces here are the "? =" in front of the "call" in the prepareCall function which sets up a place for the return value and the registerOutputParameter. It has to be registered as an Integer, as the return value is always an int (at least in SQL Server, maybe it's different in other DBs). You therefore have to get it using getInt. I tested this method and it does work.

更多推荐

从JDBC MSSQL获取返回值

本文发布于:2023-10-11 22:30:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   JDBC   MSSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!