简体   繁体   中英

How to convert Java TimeStamp into ms access Date?

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.

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! ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM