[英]How to retrieve all generated keys from multiple row PreparedStatement in Java?
Assuming the following SQL Statement: 假定以下SQL语句:
INSERT INTO MATERIAL (ID, CODE, NAME) VALUES
(NULL, 'firstCode', 'firstName'),
(NULL, 'secondCode', 'secondName');
Using the follwing code where the PreparedStatement
instance ps
represents the SQL statement from above. 使用以下代码,其中
PreparedStatement
实例ps
代表上面的SQL语句。 And the PreparedStatement
has been obtained with the option new String[]{"ID"}
in order to specify the column name of the generated keys: 并且使用选项
new String[]{"ID"}
获得了PreparedStatement
,以便指定所生成键的列名:
try {
final int affectedRows = ps.executeUpdate();
assertEquals("failed to insert all entries", "2", String.valueOf(affectedRows));
final ResultSet generatedKeys = ps.getGeneratedKeys();
while (generatedKeys.next()) {
System.out.println(generatedKeys.getInt(1));
}
} catch (SQLException e) {
// some catch block
}
The problem is that only the ID
of the second row will be retrieved. 问题在于,仅第二行的
ID
将被检索。 Do you have a suggestion how to retrieve all of the generated keys? 您有建议如何检索所有生成的密钥吗?
EDIT: 编辑:
This is the table's definition. 这是表的定义。
CREATE TABLE IF NOT EXISTS "MATERIAL" (
"ID" INT NOT NULL AUTO_INCREMENT,
"IDMATERIAL" VARCHAR(5) NOT NULL,
"NAME" VARCHAR(100) NOT NULL
);
try this, 尝试这个,
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
ResultSet rs = preparedStatement.getGeneratedKeys();
while(rs.next())
{
System.out.println(rs.getLong(1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.