【发布时间】:2012-02-10 15:46:05
【问题描述】:
我正在使用 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
// ...
}
那么,我的问题是:为什么ResultSet.getGeneratedKeys 使用GENERATED_KEY 作为列名?
【问题讨论】: