【发布时间】:2017-11-14 22:21:03
【问题描述】:
我应该从第三方 SQL Server 数据库调用存储过程(拥有只读权限)。 此外,当我尝试在 DataGrip 中执行此过程时:
EXEC Web.example_procedure 2, 3, 4
我收到了两个结果:
冷杉:
<anonymous>
-----------
3
秒:
column_1 | column_2
------------------
k1 | v1
k2 | v2
k3 | v3
...
我需要第二张桌子。
由于这个article,现在我正在做下一个
private static void executeStatement(Connection con) {
try {
String SQL = "EXEC Web.example_procedure 2, 3, 4";
Statement stmt = con.createStatement();
boolean results = stmt.execute(SQL);
int rsCount = 0;
//Loop through the available result sets.
do {
if (results) {
ResultSet rs = stmt.getResultSet();
rsCount++;
//Show data from the result set.
System.out.println("RESULT SET #" + rsCount);
while (rs.next()) {
// something will be here
}
rs.close();
}
results = stmt.getMoreResults();
} while (results);
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
输出是:
RESULT SET #1
换句话说,我只得到第一个结果。 如何获得第二张桌子?
- 我可以修改 SQL 查询吗? (这将只返回一张桌子而没有 第一个 int 结果)
- JDBC?
- 休眠?
我会很高兴任何工作变体。
更新
感谢@MarkRotteveel 和他的answer - 我解决了这个问题
String sql = "EXEC Web.example_procedure 2, 3, 4";
PreparedStatement stmt = con.prepareStatement(sql);
boolean result = stmt.execute();
while (true) {
if (result) {
ResultSet rs = stmt.getResultSet();
// in my case first table has only one column,
// and I need the second table, which has 9 columns
if (rs.getMetaData().getColumnCount() > 1) {
// go through the rows
while (rs.next()) {
// for example what we can do
rs.getMetaData().getColumnCount(); // return column count in the current result set
rs.getObject(int columnIndex); // get value for column index. Must be not greater than .getColumnCount()
}
}
} else {
int updateCount = stmt.getUpdateCount();
if (updateCount == -1) {
// no more results
break;
}
}
result = stmt.getMoreResults();
}
【问题讨论】:
-
您没有显示存储过程的代码;您可能需要考虑与结果集交错的更新计数的存在(例如,如果您的 SP 中没有
set nocount on)。results是false并不意味着没有结果,这意味着当前结果是更新计数。看看stackoverflow.com/a/14694174/466862 -
@MarkRotteveel 实际上我没有 SP 代码。但现在会要求接收它。
-
无论如何,尝试按照我在链接答案中描述的处理结果,它可能会解决您的问题。
-
@MarkRotteveel 非常感谢!真的很有帮助。
-
如果您使用 jTDS 驱动器而不是 Microsoft 驱动程序用于 SQLServer,通常会观察到此行为。在这种情况下,只要 updateCount != -1 和 result != true,@Optio 在问题的“更新”部分中就会注意到解决方案 -> 循环
标签: java sql-server hibernate jdbc