获取 CURRENT_TIMESTAMP 作为结果集的一部分

发布于 2024-10-03 15:06:35 字数 427 浏览 6 评论 0原文

除了 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.
}

is there any way of retrieving database generated values in Java other than IDENTITY fields? I can easily get IDENTITY values from a ResultSet, but I'd like to get the value of a date field which has been generated by the database (CURRENT_TIMESTAMP). I prefer not to send another SELECT query to get the date.

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.
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回首观望 2024-10-10 15:06:35

您是否尝试过类似的内容

INSERT INTO foo (bar_date) 
OUTPUT INSERTED.bar_date
VALUES (CURRENT_TIMESTAMP)

看看 OUTPUT 子句(事务 SQL)

Have you tried something like

INSERT INTO foo (bar_date) 
OUTPUT INSERTED.bar_date
VALUES (CURRENT_TIMESTAMP)

Have a look at OUTPUT Clause (Transact-SQL)

与酒说心事 2024-10-10 15:06:35

假设您使用的是 SQL 2005 或更高版本,您可以将 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
}

Assuming you're using SQL 2005 or later, you could add an OUTPUT clause to your insert statement to have it return a result set.

I'm not sure of the Java syntax to retrieve the resultset, but it would be something like the following:

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文