2016-03-29 210 views
0

如何將java中的DateTime轉換爲與MS Access數據庫匹配的格式?
這是我如何格式化日期:將DateTime插入MS Access

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
Date date = new Date(); 
String stringDate = dateFormat.format(date); 
System.out.println(stringDate); 

然後,這是我的SQL查詢:

String sql = "INSERT INTO tblBorrows(DateIn) VALUES (" + dateFormat.parse(stringDate) + ")"; 

我打印出來的stringDate,它給了我2016/03/29 16:42:24,但我的SQL是INSERT INTO tblBorrows(DateIn) VALUES (Tue Mar 29 16:42:24 SGT 2016)

這是我的異常消息: net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.4 unexpected token: MAR required:)

在我的MS Access中,我選擇通用日期作爲我的日期/時間格式: enter image description here

回答

1

變化:

String sql = "INSERT INTO tblBorrows(DateIn) VALUES (" + dateFormat.parse(stringDate) + ")"; 

String sql = "INSERT INTO tblBorrows(DateIn) VALUES (#" stringDate + "#)"; 

也許你應該嘗試做數據庫操作與準備的語句:

import java.sql.*; 

public class jdbcMsAccess { 

    public static void main(String[] args) { 
     try { 
      Connection conn = DriverManager.getConnection(
        "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};" + 
        "Dbq=C:\\__tmp\\Database1.accdb;"); 
      Date date = new Date(); 
      PreparedStatement s = conn.prepareStatement(
        "INSERT INTO tblBorrows(DateIn) VALUES (?)"); 
      s.setDate(1, new java.sql.Date(date.getTime())); 
      s.execute(); 
      s.close(); 
      conn.close(); 
     } catch (Exception e) { 
      e.printStackTrace(System.out); 
     } 

    } 
} 
+0

它給了我'不兼容的類型:日期不能轉換爲字符串' – Newbie

+0

我已經更新了答案。 – user987339

+0

現在它給了我:'net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc ::: 3.0.4意外標記:18所需:)' SQL:'INSERT INTO tblBorrows(DateIn)VALUES(2016/03/29 18:27 :30)' 我認爲'18'它是在說的是從時間'18:27:30' – Newbie

0

使用正確的分隔符的日期時間的訪問:

String sql = "INSERT INTO tblBorrows(DateIn) VALUES (#" + stringDate + "#)";