gpt4 book ai didi

java - 如何从Java中的多行PreparedStatement中检索所有生成的键?

转载 作者:行者123 更新时间:2023-12-01 06:05:29 31 4
gpt4 key购买 nike

假设有以下 SQL 语句:

INSERT INTO MATERIAL (ID, CODE, NAME) VALUES
(NULL, 'firstCode', 'firstName'),
(NULL, 'secondCode', 'secondName');

使用以下代码,其中 PreparedStatement 实例 ps 代表上面的 SQL 语句。并且已使用选项 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
}

问题是只会检索第二行的ID。您对如何检索所有生成的 key 有什么建议吗?

编辑:

这是表的定义。

CREATE TABLE IF NOT EXISTS "MATERIAL" (
"ID" INT NOT NULL AUTO_INCREMENT,
"IDMATERIAL" VARCHAR(5) NOT NULL,
"NAME" VARCHAR(100) NOT NULL
);

最佳答案

试试这个,

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
ResultSet rs = preparedStatement.getGeneratedKeys();

while(rs.next())
{
System.out.println(rs.getLong(1));
}

关于java - 如何从Java中的多行PreparedStatement中检索所有生成的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45753363/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com