2013-03-25 47 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