从MySQL数据库获取插入行的索引

时间:2010-12-19 15:15:47

标签: java sql mysql jdbc

我正在使用Java(jdbc)与MySQL数据库进行交互。我有一个主要索引的表是AUTO INCREMENT。当我插入一行时,我需要获得它刚收到的索引。我该怎么做?

3 个答案:

答案 0 :(得分:7)

来自:http://dev.mysql.com/doc/refman/5.0/en/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;

答案 1 :(得分:2)

感谢John Boker的出色回应。

如果您希望使用 PreparedStatement ,您仍然可以使用RETURN_GENERATED_KEYS,但必须采用不同的方式应用命令:

PreparedStatement ps = mysql.prepareStatement(
    "INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)",
     Statement.RETURN_GENERATED_KEYS );
ps.setString(1, "My text");
ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()););
ps.setInt(3, 5150);
ps.executeUpdate();
ResultSet results = ps.getGeneratedKeys();
results.next(); // Assume just one auto-generated key; otherwise, use a while loop here
System.out.println(results.getInt(1)); // there should only be 1 column in your results: the value of the auto-generated key
  1. RETURN_GENERATED_KEYS中添加prepareStatement()参数 功能
  2. 不是从statement.executeUpdate()获取结果,而是从中获取结果 statement.getGeneratedKeys()

答案 2 :(得分:0)

或者,使用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();