我将 H2DB 用于 litthe cuesheet-database。我正在向具有主键 ID 的 anj 自动增量字段的表中插入几条记录。对于每条记录,我想知道插入后 ID 字段的值,即在提交之前。我如何获得这个值?
问问题
932 次
1 回答
2
简而言之:
Statement.RETURN_GENERATED_KEYS
在准备插入语句时用作第二个参数ResultSet
插入后从语句中获取.getGeneratedKeys()
- 从中获取生成的 id
ResultSet
这在使用事务时也应该起作用。
以下示例演示了这一点:
try {
// register driver
Class.forName("org.h2.Driver");
// open connection, in-memory database
Connection conn = DriverManager.getConnection("jdbc:h2:mem:");
conn.setAutoCommit(false);
// create table
PreparedStatement createSample = conn.prepareStatement("CREATE TABLE sample (id int not null auto_increment, txt varchar(128))");
createSample.executeUpdate();
createSample.close();
// prepare insert statement
PreparedStatement insertStatement = conn.prepareStatement("INSERT INTO sample (txt) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
// dummy list with texts
List<String> dummyTexts = Arrays.asList("Entry A", "Entry B", "Entry C", "Entry D", "Entry E");
// insert data
for (String dummyText : dummyTexts) {
insertStatement.setString(1, dummyText);
insertStatement.executeUpdate();
// get generated key
ResultSet generatedKeys = insertStatement.getGeneratedKeys();
if ((generatedKeys != null) && (generatedKeys.next())) {
int generatedKey = generatedKeys.getInt(1);
System.out.println("generated key " + generatedKey + " for entry '" + dummyText + "'");
}
}
// commit
conn.commit();
insertStatement.close();
// select data
PreparedStatement selection = conn.prepareStatement("SELECT id, txt FROM sample");
ResultSet selectionResult = selection.executeQuery();
while (selectionResult.next()) {
System.out.println("id: " + selectionResult.getInt(1) + ", txt: '" + selectionResult.getString(2) + "'");
}
selectionResult.close();
selection.close();
// close connection
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
于 2018-02-03T22:52:42.467 回答