“通用"使用JDBC的当前时间函数 [英] "Generic" current time function using JDBC
问题描述
当我们使用JPA和JPQL时,我们可以使用一些日期/时间表达式,使查询DMBS独立.例如,假设我要在数据库中设置会话的结束时间,则可以简单地使用CURRENT_TIMESTAMP
表达式,如下所示:
When we work with JPA and JPQL we can use some date/time expressions which make the query DMBS independent. For instance let's say if I want to set the ending time of a session in my database I could simply use CURRENT_TIMESTAMP
expression as follows:
String jpql = "UPDATE SessionJpa s SET s.end = CURRENT_TIMESTAMP WHERE s.id = :id";
entityManager.getTransaction().begin();
Query query = entityManager.createQuery(jpql);
query.setParameter("id", someIdValue);
query.executeUpdate();
entityManager.getTransaction().commit();
这样,同一JPQL应该可以与DBMS一起用于Oracle,MySQL,PostreSQL等.
This way the same JPQL should work with Oracle, MySQL, PostreSQL, etc as DBMS.
现在我的问题是:使用JDBC而不是JPA时是否可以实现相同的目的?
Now my question: Is there a way to achieve the same when using JDBC instead of JPA?
这是我到目前为止所拥有的:
This is what I have so far:
String sql = "UPDATE Sessions SET end = SYSDATE WHERE id = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, someIdValue);
int updatedRows = statement.executeUpdate();
} catch(SQLException ex) {
Logger.getLogger(SessionsBean.class.getName()).log(Level.SEVERE, null, ex);
}
但是SYSDATE
当然不是通用表达式,它最有可能仅与Oracle作为DBMS一起使用.
But of course SYSDATE
is not a generic expression and it will work only with Oracle as DBMS most likely.
推荐答案
您可以在此处找到相关的讨论- Oracle的CURRENT_TIMESTAMP函数是否真的是一个功能?.
You can find a related discussion here - Is Oracle's CURRENT_TIMESTAMP function really a function?.
总结是-CURRENT_TIMESTAMP
是由SQL标准定义的,任何兼容的数据库系统都应该识别它.
Summary is that - CURRENT_TIMESTAMP
is defined by the SQL standard and any compliant database system should recognize it.
这篇关于“通用"使用JDBC的当前时间函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!