2010-12-19 32 views
8

我正在使用Java(jdbc)与MySQL数据库交互。我有一个主要索引是自动增量表。当我插入一行时,我需要获取它刚收到的索引。我怎么做?从MySQL数据库获取插入行的索引

+0

如何利用此索引搜索更快的激光? – David 2010-12-19 15:22:54

+2

@大卫:你是什么意思?主键始终是索引,因此如果查询索引,将总是有助于更快地搜索。问一个单独的问题,如果你想更多的说明:) – Konerak 2010-12-19 15:44:00

+0

我认为主键可以索引,而不是本身的索引。我相信它是完全有效的(尽管通常不推荐)使用varchar(60)作为主键。然后检索刚刚插入的主键的索引而不是值本身会很有趣。更具体地说,在存储最后一条记录的磁盘上获得某种位置会很有用,所以如果事实证明它应该被修改(例如由于用户单击了撤消按钮),可以快速修改它, 。希望我现在不劫持这个步伐... – David 2010-12-20 14:54:42

回答

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; 
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(); 
2

感谢约翰·博克的出色的响应。

如果您希望使用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 PARAM在prepareStatement() 功能。
  2. statement.executeUpdate()得到的结果不是 statement.getGeneratedKeys()