gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:48:08 26 4
gpt4 key购买 nike

我正在玩 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com