1

I wrote a simple program which creates table and allow to insert text and date to database. I found here How to convert LocalDate to SQL Date Java? how to convert LocalDate to SQL Date format. But after inserting the date to database it is 694220400000 (UNIX time?) instead of 1992-01-01. Can anyone tell me what am I doing wrong? Or in SQLite it won't work and I have to convert it to String?

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();
    }

}
Community
  • 1
  • 1
ketrab321
  • 541
  • 2
  • 12
  • 22

1 Answers1

1

DATE is an alias for integer. Define 'date' of type TEXT to get an readable date (ISO8601)

https://sqlite.org/datatype3.html

Stéphane
  • 161
  • 1
  • 6