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

标签 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
   // ...
}

那么,我的问题是:为什么 ResultSet.getGeneratedKeys 使用 GENERATED_KEY 作为列名?

最佳答案

You shouldn't retrieve these columns by name. Only by index, since there can only ever be one column with MySQL and auto_increments that returns value(s) that can be exposed by Statement.getGeneratedKeys().

Currently the MySQL server doesn't return information directly that would make the ability to retrieve these columns by name in an efficient manner possible, which is why I'm marking this as "to be fixed later", since we can, once the server returns the information in a way that the driver can use.

来自 here (2006 年!)。

关于java - 为什么 getGeneratedKeys() 返回 "GENERATED_KEY"作为列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8867521/

相关文章:

java - 在servlet中包含一个jsp的内容

java - Rhino、typeof 和自动装箱混淆

mysql - 帮忙用 SQL 脚本看看你的购物篮里有什么?

java - 数据每 24 小时刷新一次

java - 在 Spinner Android 上显示具有不同返回值的文本

sql - 如何计算具有 HAVING 条件的 MySQL 条目

mysql - 使用 TypeScript 时,Sequelize 在 findAndCountAll() 中生成错误的 SQL 语句

java - ArrayList 重复数据库中的相同数据?

java - JDBC 结果集 - 没有可用数据

java - Oracle 是 Java 中 BINARY_INTEGER 类型的 NUMBER(5) 索引表吗?