Why does getGeneratedKeys () return "GENERATED_KEY" as the column name?

I play with JDBC / MySQL 5.1. I created an insert query to insert some data into a table and want to return the generated key from the row just created. However, when I go to the link to the "id" column, which is my PK column and auto-increment.

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

So my question is: Why ResultSet.getGeneratedKeys use GENERATED_KEY as the column name?

+6
source share
1 answer

You should not retrieve these columns by name. Only by index, since there can only be one column with MySQL and auto_increments, which returns the values ​​(s) that Statement.getGeneratedKeys () can be exposed.

Currently, the MySQL server does not return information directly, it will be possible to retrieve these columns by name in perhaps, so I mark this as β€œbe fixed later”, since we can as soon as the server returns the information in the way the driver can use it.

From here (in 2006!).

+3
source

Source: https://habr.com/ru/post/906009/


All Articles