【问题标题】:Inserting LocalDate to SQLite database将 LocalDate 插入 SQLite 数据库
【发布时间】:2017-05-26 15:38:31
【问题描述】:

我编写了一个简单的程序来创建表格并允许将文本和日期插入数据库。我在这里找到了How to convert LocalDate to SQL Date Java? 如何将 LocalDate 转换为 SQL 日期格式。但是在将日期插入数据库后,它是 694220400000(UNIX 时间?)而不是 1992-01-01。谁能告诉我我做错了什么?或者在 SQLite 中它不起作用,我必须将其转换为字符串?

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        Connection conn = null;
        LocalDate date;
        Statement stmt = null;
        PreparedStatement prepStmt = null;

        try {
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection("jdbc:sqlite:Test.db");
            stmt = conn.createStatement();
            System.out.println("Connected to Database");
        } catch (ClassNotFoundException e) {
            System.err.println("No JDBC driver");
        } catch (SQLException e) {
            System.err.println("Error during connecting");
        }

        String createTest = "CREATE TABLE IF NOT EXISTS test ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'text' TEXT, 'date' Date)";
        try {
            stmt.execute(createTest);
        } catch (SQLException e) {
            System.err.println("Error during creating table");
        }

        date = LocalDate.of(1992, 1, 1);
        Date dat = Date.valueOf(date);
        System.out.println(dat);

        String query = "insert into test values(NULL, ?, ?)";
        System.out.println("Type text");
        String text = input.nextLine();

        try {
            prepStmt = conn.prepareStatement(query);
            prepStmt.setString(1, text);
            prepStmt.setDate(2, dat);
            prepStmt.execute();
        } catch (SQLException e) {
            System.err.println("Error");
        }

        input.close();
    }

}

【问题讨论】:

    标签: java sql database


    【解决方案1】:

    DATE 是整数的别名。定义 TEXT 类型的“日期”以获取可读日期 (ISO8601)

    https://sqlite.org/datatype3.html

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多