简体   繁体   English

使用Microsoft JDBC驱动程序的SELECT INTO查询影响的行数

[英]Count of rows affected by SELECT INTO query with Microsoft JDBC driver

Is there a way to get a "rows affected" result for 有没有办法获得“行受影响”的结果

SELECT * INTO TableB FROM TableA

with Microsoft's JDBC driver for SQL Server? 使用Microsoft的SQL Server JDBC驱动程序? When I execute that query in SQL Server Management Studio it returns the number of rows the same way as it does for DELETE, INSERT, or UPDATE. 当我在SQL Server Management Studio中执行该查询时,它以与DELETE,INSERT或UPDATE相同的方式返回行数。

I tried executeQuery but it doesn't return a ResultSet . 我尝试了executeQuery但它没有返回ResultSet I tried executeUpdate but I always get -1 as result, and I tried execute , but the return value seems to be false so there is no ResultSet . 我尝试了executeUpdate但我总是得到-1作为结果,我尝试execute ,但返回值似乎是false所以没有ResultSet I've downloaded the MS JDBC driver 6.0 from 31.01.2017 because I read about problems with older versions. 我从2017年1月31日起下载了MS JDBC驱动程序6.0,因为我读到了旧版本的问题。

Update: This issue has been fixed in version 6.1.5 of the JDBC Driver for SQL Server. 更新:此问题已在SQL Server的JDBC驱动程序的6.1.5版中得到修复。


(previous answer) (上一个答案)

Testing confirms that even with the most recent Microsoft JDBC driver (6.0.8112.100) 测试确认即使使用最新的Microsoft JDBC驱动程序(6.0.8112.100)

 sql = "SELECT * INTO TableB FROM TableA"; try (Statement st = conn.createStatement()) { int n = st.executeUpdate(sql); System.out.printf("%d row(s) affected", n); } 

produces 产生

 -1 row(s) affected 

while the jTDS driver correctly returns the actual number of rows: 而jTDS驱动程序正确返回实际行数:

 3 row(s) affected 

A workaround for the Microsoft JDBC driver would be to use an anonymous code block to return a ResultSet containing @@ROWCOUNT Microsoft JDBC驱动程序的解决方法是使用匿名代码块返回包含@@ROWCOUNT的ResultSet

 sql = "SET NOCOUNT ON; " + "SELECT * INTO TableB FROM TableA; " + "SELECT @@ROWCOUNT AS n; "; try ( Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) { rs.next(); int n = rs.getInt(1); System.out.printf("%d row(s) affected", n); } 

which does correctly return 哪个正确返回

 3 row(s) affected 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM