java - 書き方 - jdbc mysql
MySQLデータベースから挿入された行のインデックスを取得する (2)
私はJavaデータベース(jdbc)を使ってMySQLデータベースとやり取りしています。 私は、AUTO INCREMENTのプライマリインデックスを持つテーブルを持っています。 行を挿入すると、今受け取ったインデックスを取得する必要があります。 それ、どうやったら出来るの?
投稿者 : http : //dev.mysql.com/doc/refman/5.0/ja/connector-j-usagenotes-basic.html#connector-j-usagenotes-last-insert-id
stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')",
Statement.RETURN_GENERATED_KEYS);
//
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
//
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
// throw an exception from here
}
rs.close();
rs = null;
あるいは、Spring JDBCを使用すると、次のようになります。
Map<String, Object> map = new HashMap<String, Object>();
map.put("column1", "test");
map.put("column2", Boolean.TRUE);
SimpleJdbcInsert insert = new SimpleJdbcInsert(template).withTableName("table").usingGeneratedKeyColumns("id");
int id = insert.executeAndReturnKey(map).intValue();