- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
如何通过java.time插入和获取 LocalDate
类型(例如JDBC)到SQL数据库(例如H2 Database Engine)?
使用 PreparedStatement::setDate
和 ResultSet::getDate
的旧方法适用于旧版 java.sql.Date
类型。我想避免使用这些麻烦的旧日期时间类。
通过JDBC driver发送java.time类型的现代方法是什么?
最佳答案
我们有两种通过JDBC交换java.time对象的途径:
java.util.Date
,
java.util.Calendar
)和相关的
java.sql
类(例如
java.sql.Date
)实在是一团糟。它们采用设计不当的黑客手段构建而成,被证明是有缺陷,麻烦且令人困惑的。尽可能避免使用它们。现在由java.time类取代。
setLocalDate
/
getLocalDate
各种方法,而是添加了
setObject
/
getObject
方法。
PreparedStatement::setObject
即可。驱动程序检测到传递的参数的Java类型,并将其转换为适当的SQL类型。将Java
LocalDate
转换为SQL
DATE
类型。有关这些映射的列表,请参见
JDBC Maintenance Release 4.2 PDF文档的第22节。
myPreparedStatement.setObject ( 1 , myLocalDate ); // Automatic detection and conversion of data type.
要从数据库检索数据,请调用
ResultSet::getObject
。除了传递最终的
Object
对象,我们还可以传递一个额外的参数,即我们希望接收的数据类型的
Class
。通过指定期望的类,我们获得了
type-safety和编译器检查并验证的
IDE。
LocalDate localDate = myResultSet.getObject ( "my_date_column_" , LocalDate.class );
这是一个完整的工作示例应用程序,显示了如何在H2数据库中插入和选择
LocalDate
值。
package com.example.h2localdate;
import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.UUID;
/**
* Hello world!
*/
public class App {
public static void main ( String[] args ) {
App app = new App ( );
app.doIt ( );
}
private void doIt ( ) {
try {
Class.forName ( "org.h2.Driver" );
} catch ( ClassNotFoundException e ) {
e.printStackTrace ( );
}
try (
Connection conn = DriverManager.getConnection ( "jdbc:h2:mem:trash_me_db_" ) ;
Statement stmt = conn.createStatement ( ) ;
) {
String tableName = "test_";
String sql = "CREATE TABLE " + tableName + " (\n" +
" id_ UUID DEFAULT random_uuid() PRIMARY KEY ,\n" +
" date_ DATE NOT NULL\n" +
");";
stmt.execute ( sql );
// Insert row.
sql = "INSERT INTO test_ ( date_ ) " + "VALUES (?) ;";
try ( PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ; ) {
LocalDate today = LocalDate.now ( ZoneId.of ( "America/Montreal" ) );
preparedStatement.setObject ( 1, today.minusDays ( 1 ) ); // Yesterday.
preparedStatement.executeUpdate ( );
preparedStatement.setObject ( 1, today ); // Today.
preparedStatement.executeUpdate ( );
preparedStatement.setObject ( 1, today.plusDays ( 1 ) ); // Tomorrow.
preparedStatement.executeUpdate ( );
}
// Query all.
sql = "SELECT * FROM test_";
try ( ResultSet rs = stmt.executeQuery ( sql ) ; ) {
while ( rs.next ( ) ) {
//Retrieve by column name
UUID id = rs.getObject ( "id_", UUID.class ); // Pass the class to be type-safe, rather than casting returned value.
LocalDate localDate = rs.getObject ( "date_", LocalDate.class ); // Ditto, pass class for type-safety.
//Display values
System.out.println ( "id_: " + id + " | date_: " + localDate );
}
}
} catch ( SQLException e ) {
e.printStackTrace ( );
}
}
}
运行时。
id_: e856a305-41a1-45fa-ab69-cfa676285461 | date_: 2017-03-26
id_: a4474e79-3e1f-4395-bbba-044423b37b9f | date_: 2017-03-27
id_: 5d47bc3d-ebfa-43ab-bbc2-7bb2313b33b0 | date_: 2017-03-28
LocalDate
转换为
java.sql.Date
对象。
java.sql.Date mySqlDate = java.sql.Date.valueOf( myLocalDate );
然后传递给
PreparedStatement::setDate
方法。
preparedStatement.setDate ( 1, mySqlDate );
要从数据库中检索,请调用
ResultSet::getDate
以获取
java.sql.Date
对象。
java.sql.Date mySqlDate = myResultSet.getDate( 1 );
然后立即将其转换为
LocalDate
。您应该尽可能简短地处理java.sql对象。仅使用java.time类型执行所有业务逻辑和其他工作。
LocalDate myLocalDate = mySqlDate.toLocalDate();
这是一个完整的示例应用程序,显示了H2数据库中java.sql类型与java.time类型的结合使用。
package com.example.h2localdate;
import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.UUID;
/**
* Hello world!
*/
public class App {
public static void main ( String[] args ) {
App app = new App ( );
app.doIt ( );
}
private void doIt ( ) {
try {
Class.forName ( "org.h2.Driver" );
} catch ( ClassNotFoundException e ) {
e.printStackTrace ( );
}
try (
Connection conn = DriverManager.getConnection ( "jdbc:h2:mem:trash_me_db_" ) ;
Statement stmt = conn.createStatement ( ) ;
) {
String tableName = "test_";
String sql = "CREATE TABLE " + tableName + " (\n" +
" id_ UUID DEFAULT random_uuid() PRIMARY KEY ,\n" +
" date_ DATE NOT NULL\n" +
");";
stmt.execute ( sql );
// Insert row.
sql = "INSERT INTO test_ ( date_ ) " + "VALUES (?) ;";
try ( PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ; ) {
LocalDate today = LocalDate.now ( ZoneId.of ( "America/Montreal" ) );
preparedStatement.setDate ( 1, java.sql.Date.valueOf ( today.minusDays ( 1 ) ) ); // Yesterday.
preparedStatement.executeUpdate ( );
preparedStatement.setDate ( 1, java.sql.Date.valueOf ( today ) ); // Today.
preparedStatement.executeUpdate ( );
preparedStatement.setDate ( 1, java.sql.Date.valueOf ( today.plusDays ( 1 ) ) ); // Tomorrow.
preparedStatement.executeUpdate ( );
}
// Query all.
sql = "SELECT * FROM test_";
try ( ResultSet rs = stmt.executeQuery ( sql ) ; ) {
while ( rs.next ( ) ) {
//Retrieve by column name
UUID id = ( UUID ) rs.getObject ( "id_" ); // Cast the `Object` object to UUID if your driver does not support JDBC 4.2 and its ability to pass the expected return type for type-safety.
java.sql.Date sqlDate = rs.getDate ( "date_" );
LocalDate localDate = sqlDate.toLocalDate (); // Immediately convert into java.time. Mimimize use of java.sql types.
//Display values
System.out.println ( "id_: " + id + " | date_: " + localDate );
}
}
} catch ( SQLException e ) {
e.printStackTrace ( );
}
}
}
为了好玩,让我们尝试另一个。这次从中获取连接的
using a DataSource
implementation。这次尝试使用
LocalDate.MIN
,它在ISO 8601(-999999999-01-01)中是大约十亿年前的常数。
package work.basil.example;
import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.UUID;
public class LocalDateMin
{
public static void main ( String[] args )
{
LocalDateMin app = new LocalDateMin();
app.doIt();
}
private void doIt ()
{
org.h2.jdbcx.JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
ds.setURL( "jdbc:h2:mem:localdate_min_example_db_;DB_CLOSE_DELAY=-1" );
ds.setUser( "scott" );
ds.setPassword( "tiger" );
try (
Connection conn = ds.getConnection() ;
Statement stmt = conn.createStatement() ;
)
{
String tableName = "test_";
String sql = "CREATE TABLE " + tableName + " (\n" +
" id_ UUID DEFAULT random_uuid() PRIMARY KEY ,\n" +
" date_ DATE NOT NULL\n" +
");";
stmt.execute( sql );
// Insert row.
sql = "INSERT INTO test_ ( date_ ) " + "VALUES (?) ;";
try ( PreparedStatement preparedStatement = conn.prepareStatement( sql ) ; )
{
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
preparedStatement.setObject( 1 , LocalDate.MIN ); // MIN =
preparedStatement.executeUpdate();
}
// Query all.
sql = "SELECT * FROM test_";
try ( ResultSet rs = stmt.executeQuery( sql ) ; )
{
while ( rs.next() )
{
//Retrieve by column name
UUID id = rs.getObject( "id_" , UUID.class ); // Pass the class to be type-safe, rather than casting returned value.
LocalDate localDate = rs.getObject( "date_" , LocalDate.class ); // Ditto, pass class for type-safety.
//Display values
System.out.println( "id_: " + id + " | date_: " + localDate );
}
}
} catch ( SQLException e )
{
e.printStackTrace();
}
}
}
id_: 4b0ba138-d7ae-469b-854f-5cbe7430026f | date_: -999999999-01-01
java.util.Date
,
Calendar
和
SimpleDateFormat
。
java.sql.*
类。 Hibernate 5和JPA 2.2支持java.time。
Interval
,
YearWeek
,
YearQuarter
和
more。
关于java - 在SQL数据库(例如H2)中插入和获取java.time.LocalDate对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43039614/
在尝试 time 的 python 执行时,我发现在一条语句中两次调用 time.time() 时出现奇怪的行为。在语句执行期间获取time.time() 有一个非常小的处理延迟。 例如time.ti
我要疯了。对于我的生活,我无法弄清楚为什么以下代码会导致 Unity 在我按下播放键后立即卡住。这是一个空的项目,脚本附加到一个空的游戏对象。在控制台中,什么也没有出现,甚至没有出现初始的 Debug
我要疯了。对于我的生活,我无法弄清楚为什么以下代码会导致 Unity 在我按下播放键后立即卡住。这是一个空的项目,脚本附加到一个空的游戏对象。在控制台中,什么也没有出现,甚至没有出现初始的 Debug
我不明白为什么下面的结果是一样的。我预计第一个结果是指针地址。 func print(t *time.Time) { fmt.Println(t) // 2009-11-10 23:00:00
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help
当我有一个time.Time时: // January, 29th t, _ := time.Parse("2006-01-02", "2016-01-29") 如何获得代表 1 月 31 日的 ti
首先,我意识到不推荐使用 time with time zone。我要使用它是因为我将多个 time with time zone 值与我当前的系统时间进行比较,而不管是哪一天。 IE。用户说每天 0
长期以来,在 Rust 中精确测量时间的标准方法是 time crate 及其 time::precise_time_ns功能。但是,time crate 现在已被弃用,std 库有 std::tim
我正在我学校的一个科学集群上运行我的有限差分程序。该程序使用 openmpi 来并行化代码。 当程序连续运行时,我得到: real 78m40.592s user 78m34.920s s
尽管它们已被弃用并且有比 time 更好的模块(即 timeit),但我想知道这两个函数 time 之间的区别.clock() 和 time.time()。 从后者 (time.time()) 开始,
这个问题在这里已经有了答案: Python's time.clock() vs. time.time() accuracy? (16 个答案) 关闭 6 年前。 我认为两者都衡量时间量?但是他们返回
我正在尝试测试 http 请求处理代码块在我的 Flask Controller 中需要多长时间,这是我使用的示例代码: cancelled = [] t0 = time.time() t1 = ti
运行 python 的计算机时钟(Windows 或 Linux)时会发生什么自动更改并调用 time.time()? 我读到,当时钟手动更改为过去的某个值时,time.time() 的值会变小。 最
我有一个结构可能无法在其字段之一上设置 time.Time 值。测试无效性时,我不能使用 nil 或 0。time.Unix(0,0) 也不相同。我想到了这个: var emptyTime time.
我有一个打算用数据库记录填充的结构,其中一个日期时间列可以为空: type Reminder struct { Id int CreatedAt time.Time
问题陈述:通过匹配其百分比随机执行各种命令。比如执行 CommandA 50% 的时间和 commandB 25% 的时间和 commandC 15% 的时间等等,总百分比应该是 100%。 我的问题
我正在使用 laravel 6。我在同一个应用程序中有类似的 Controller 和类似的 View ,它工作正常。对比之后还是找不到错误。 Facade\Ignition\Exceptions\V
我需要用 ("%m/%d/%Y %H:%M:%S") 格式表示时间,我得到的浮点值是 time.time(). 我已经有了一个 time.time() 形式的值。例如,我已经有一个值,我每 0.3 秒
我正在使用以下方法获取 utc 日期时间: import datetime import time from pytz import timezone now_utc = datetime.datet
我在 Ubuntu 上使用 time.clock 和 time.time 为一段 python 代码计时: clock elapsed time: 8.770 s time elapsed time
我是一名优秀的程序员,十分优秀!