SQLite JDBC rs.getDate()getTimestamp()等都返回错误的值

Oma*_*ohl 6 sqlite datetime timestamp date jdbc

由于某种原因使用JDBC for SQLite时,Date和Timestamp值正确存储在DB中,在使用命令行sqlite3工具时正确显示,但使用ResultSet函数检索这些值时,它不起作用.下面是一个小型测试类,演示了我的意思.

import java.sql.*;

public class Test {
  public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
    Statement stat = conn.createStatement();
    stat.executeUpdate("drop table if exists people;");
    stat.executeUpdate("create table people (name, occupation, date date);");
stat.executeUpdate("insert into people values ('Turing', 'Computers', date('now'));");

    ResultSet rs = stat.executeQuery("select * from people;");
    while (rs.next()) {
      System.out.println("name = " + rs.getString("name"));
      System.out.println("job = " + rs.getString("occupation"));
      System.out.println("date = " + rs.getDate("date"));
      System.out.println("dateAsString = " + rs.getString("date"));
    }
    rs.close();
    conn.close();
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

name =图灵
作业=计算机
日期= 1970-01-01
dateAsString = 2011-03-24

Mar*_*ijn 9

像Scott说的那样:SQLite没有Date类型.

您可以让SQLite使用strftime函数为您进行转换:strftime('%s', date).然后你可以rs.getDate在Java端使用.

您还可以将SQLite日期检索为字符串,并将其解析为日期:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date today = df.parse(rs.getString("date"));
    System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
   e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)