How to convert Java TimeStamp into ms access Date?

2019-03-02 06:32发布

问题:

I would like to insert a java Timestamp into an msaccess database but I am getting an error which is listed below. The ms-access field has been set to a DATE datatype. Any advise would be deeply appreciated. Thanks

Here's my DAO class method:

public void addSale(String saleDetails, String saleTotal, Timestamp saleTimestamp) 
                    throws ClassNotFoundException, SQLException {

Statement myStatement = getConnection();
String sql = "INSERT INTO Sale (SaleDetails, SaleTotal, SaleTimestamp)"
            + " VALUES ('"+saleDetails+"','"+saleTotal+"','"+saleTimestamp+"')";

myStatement.executeUpdate(sql);
closeConnection();

My DTO method:

public void storeSale(String saleDetails, String saleTotal, Timestamp saleTimestamp){
   DAO dao = DAO.getDAO();
   try {
      dao.addSale(saleDetails, saleTotal, saleTimestamp);
    } catch (ClassNotFoundException | SQLException ex) {
        Logger.getLogger(Sale.class.getName()).log(Level.SEVERE, null, ex);
    }

My Timestamp method:

public Timestamp addTimestamp(){ 
    java.util.Date date= new java.util.Date();
return new Timestamp(date.getTime());
}

Error: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.

回答1:

You need to convert your java.util.Data to a java.sql.Date or if you need the precision of the java.sql.Timestamp change your Database type to TIMESTAMP

some code to create a java.sql.Date:

 java.util.Date today = new java.util.Date();
 long t = today.getTime();
 java.sql.Date dt = new java.sql.Date(t);

You can then put the java.sql.Date in your Database, did always work for me.

For Info:

  • java.sql.Date corresponds to SQL DATE it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally sql.Date isn't tied to timezones.
  • java.sql.Time corresponds to SQL TIME andonly contains information about hour, minutes, seconds and milliseconds.
  • java.sql.Timestamp corresponds to SQL TIMESTAMP which is the date to the nanosecond (note that util.Date only supports milliseconds!).