2017-01-11 139 views
0

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

} 

回答