2013-03-25 49 views
0

我通過java連接mysql。我試圖插入一條記錄,並使用statement.getGeneratedKeys()然後if (generatedKeys.next())找到狀態。現在我可以得到一個coulmn的值插入(即)我有列命名通過,它是一個auto_increament列,它是我的主鍵,現在我想要獲取插入此列中的值。可能嗎??在MySQL中使用statement.getGeneratedKeys()時可以獲得自動生成的值嗎?

+0

AFAIK,MySQL不允許非主鍵列自動遞增。你有沒有誤認你的問題? – Perception 2013-03-25 12:39:08

+0

@感知我的錯誤,我錯過了:) – 2013-03-25 12:41:09

回答

2

標準的MySQL Connector J驅動程序確實支持獲取生成的密鑰,是的。以下是一些示例代碼:

final Connection conn ; // setup connection 
final String SQL ; // define SQL template string 

final PreparedStatement stmt = connection.prepareStatement(
    SQL, 
    Statement.RETURN_GENERATED_KEYS); 

int affected = stmt.executeUpdate(); 
if (affected > 0) { 
    final ResultSet keySet = stmt.getGeneratedKeys(); 
    while (keySet.next()) { 
     // these are your autogenerated keys, do something with them 
     System.out.println(keySet.getInt(1)); 
    } 
} 
+0

仍然我越來越java.sql.SQLException:列「傳遞」未找到錯誤。 – 2013-03-25 12:52:43

+0

您不會在迭代生成的密鑰時獲取該信息。你確定你的insert語句不與你的表模式不匹配嗎? – Perception 2013-03-25 13:11:26