Lar*_*ohl 5 java timezone jdbc sqldatetime java-8
我想LocalDate在一个DATE列中存储一个并保持不变.这两个DATE和LocalDate是"本地"类型的定义.因此,时区的概念不应以任何方式干涉.
下面的代码是一个最小的示例,它创建DATE一个在内存数据库中包含列的表.maven工件com.h2database:h2:1.4.192必须位于类路径中.
首先,定义方法insert和retrieve:
static void insert(DataSource ds, String date) throws SQLException {
try (Connection conn = ds.getConnection();
Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE people (id BIGINT NOT NULL AUTO_INCREMENT"
+ ", born DATE NOT NULL, PRIMARY KEY (id) );");
stmt.execute("INSERT INTO people (born) VALUES ('" + date + "')");
}
}
static LocalDate retrieve(DataSource ds) throws SQLException {
try (Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM people limit 1")) {
if (rs.next()) {
java.sql.Date retrieved = java.sql.Date.valueOf(rs.getString("born"));
return retrieved.toLocalDate();
}
throw new IllegalStateException("No data");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,该insert方法使用单引号中的toString值LocalDate,因此Java™没有机会创建时区歧义.现在调用insert一次然后多次retrieve,每次使用不同的timzone设置:
public static void main(String[] args) throws Exception {
DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test", "sa", "sa");
LocalDate born = LocalDate.parse("2015-05-20");
insert(ds, born.toString());
System.out.println("Inserted: " + born);
for (int i : new int[]{-14, 0, 12}) {
TimeZone z = TimeZone.getTimeZone(String.format("Etc/GMT%+02d", i));
TimeZone.setDefault(z);
System.out.println("Retrieved: " + retrieve(ds));
}
}
Run Code Online (Sandbox Code Playgroud)
然后打印以下内容:
Inserted: 2015-05-20 Retrieved: 2015-05-20 Retrieved: 2015-05-19 Retrieved: 2015-05-18
如何编写retrieve方法以便它返回无条件插入的相同值,假设数据库表没有更改?
我刚刚尝试对您的方法进行以下修改retrieve,它对我有用:
日期数据类型。格式为年-月-日。
所以,而不是你的...
java.sql.Date retrieved = (java.sql.Date) rs.getObject("born");
return retrieved.toLocalDate();
Run Code Online (Sandbox Code Playgroud)
...我刚刚用过...
return LocalDate.parse(rs.getString("born"));
Run Code Online (Sandbox Code Playgroud)
...我的代码产生了
Inserted: 2015-05-20
Retrieved: 2015-05-20
Retrieved: 2015-05-20
Retrieved: 2015-05-20
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4580 次 |
| 最近记录: |