2010-12-19 101 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()