简体   繁体   中英

How to insert a date in MySQL database using Java?

I have given date type and timestamp data type (4/2/2015 3:10:36 PM) also but I am getting below error. This date I am calling from XLSX sheet.

Exception in thread "main" com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '4/2/2015 3:10:36 PM' for column 'date' at row 1
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4235)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2825)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
    at com.tasc.xls.SearchExcel.main(SearchExcel.java:64)

You are probably passing the date as a string in your prepared statement instead of passing it as a Date type. Passing it as a date type will send correctly your date to mysql.

Example:

PreparedStatement pstmt = con.prepareStatement("UPDATE my_table set my_date = ?");
pstmt.setDate(1, yourDateConvertedIntoDateType);

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