有没有办法在除IDENTITY字段之外的Java中检索数据库生成的值?我可以轻松地从ResultSet获取IDENTITY值,但我想获取数据库生成的日期字段的值(CURRENT_TIMESTAMP)。我不想发送另一个SELECT查询来获取日期。
statement = connection.prepareStatement("INSERT INTO foo (bar_date) VALUES (CURRENT_TIMESTAMP)");
ResultSet generatedKey = statement.getGeneratedKeys();
while (generatedKey.next()) {
// read the key..., this unfortunately only returns IDENTITY columns.
}
答案 0 :(得分:2)
你有没有试过像
这样的东西INSERT INTO foo (bar_date)
OUTPUT INSERTED.bar_date
VALUES (CURRENT_TIMESTAMP)
答案 1 :(得分:0)
假设您使用的是SQL 2005或更高版本,可以在insert语句中添加OUTPUT
子句,以使其返回结果集。
我不确定要检索结果集的Java语法,但它将类似于以下内容:
statement = connection.prepareStatement("INSERT INTO foo OUTPUT inserted.id, inserted.bar_date (bar_date) VALUES (CURRENT_TIMESTAMP)"); //guessing the name of the id column
ResultSet returnSet = statement.execute(); // or however you do this
while (resultset.next()) {
// resultset will have two columns - id and bar_date
}