为什么getGeneratedKeys()将"GENERATED_KEY"作为列名返回?

Zac*_*ack 6 java mysql jdbc

我正在玩JDBC/MySQL 5.1.我创建了一个insert查询,将一些数据插入到表中,并希望从新创建的行返回生成的键.但是,当我通过"id"引用列时,这是我的PK和自动增量列.

PreparedStatement ps = St0rm.getInstance().getDatabase("main")
        .prepare("INSERT INTO quests (name,minlevel,start_npc,end_npc) VALUES(?,?,?,?)", true); // creates a prepared statement with flag RETURN_GENERATED_KEYS

// ...

int affected = ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
if (affected > 0 && keys.next()) {
   St0rm.getInstance().getLogger().warning(String.format("ID Column Name: %s", keys.getMetaData().getColumnName(1))); // says the column name is: GENERATED_KEY

   q = new Quest(keys.getInt(1)); // column index from the generated key, no error thrown.

   q = new Quest(keys.getInt("id")); // actual column name, line throws a SQLException
   // ...
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题:为什么ResultSet.getGeneratedKeys使用GENERATED_KEY列名?

Ski*_*ead 6

您不应按名称检索这些列。仅通过索引,因为 MySQL 和 auto_increments 只能有一列返回可以由 Statement.getGeneratedKeys() 公开的值。

目前 MySQL 服务器不直接返回信息,这将使能够以有效的方式按名称检索这些列的能力成为可能,这就是为什么我将其标记为“稍后修复”,因为我们可以,一旦服务器以驱动程序可以使用的方式返回信息。

这里开始(2006 年!)。