2012-11-15 46 views
1

我試圖返回更新的受影響行的ID。我想知道,爲什麼我沒有從這裏得到ResultSet(只有主鍵可以),儘管我設置了Statement.RETURN_GENERATED_KEYS?我使用最新的jTDS驅動程序1.3.0連接到Microsoft SQL Server。從update語句返回ResultSet?

try 
    { 
     PreparedStatement pst = SQL.getConnection().prepareStatement(qry, Statement.RETURN_GENERATED_KEYS); 

     pst.setString(1, someValue); 
     pst.setString(2, someOtherValue); 

     int affectedRows = pst.executeUpdate(); 
     System.out.println(affectedRows); //to make sure whether the query updated anything 

     ResultSet rs = pst.getGeneratedKeys(); 

     if (rs.next()) 
     { 
      System.out.println(rs.getInt(1)); 
     } 
    } catch (Exception e) { 
     e.printStacktTrace(); 
    } 

此處有任何建議嗎?

+0

什麼是查詢?正在生成哪些密鑰? – Thilo

+1

是您試圖檢索自動增量列的關鍵? – PermGenError

+0

這是哪個錯誤? rs'null?沒有'rs.next()'? 'rs.getInt(1)'失敗?如果你想要任何有意義的援助,請更具體。 – SJuan76

回答

0

一種解決方法是創建存儲過程並使用CallableStatement方法調用它。不要問我爲什麼這樣做,而不是其他方式。

+0

我正在使用callableStatement調用使用'callableStatement.executeUpdate()'的存儲過程,但我仍然收到此錯誤。 我正在用一個循環從同一個地方調用多個存儲過程。但是這個問題只發生在一個存儲過程中。 請指教。 –

0

使用SQL Server 2008及更高版本,您可以在INSERT或UPDATE語句中使用OUTPUT clause。例如,請參閱this answer