简体   繁体   中英

Why do I get a “com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value:” error?

I am trying to set the the created_at column time created_at DATETIME NOT NULL in my table on OPENSHIFT to my local time of Kopenhagen . How can I set the time in the openshift server to my localtime? At the moment I am getting this error com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '16.05.2015 22:28:13' for column 'created_at' at row 1 at this line prep.executeQuery();

I appreciate any help.

stt.execute("CREATE TABLE IF NOT EXISTS bus"
                    + "(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
                    + "mac VARCHAR(30) NOT NULL UNIQUE,"
                    + "route int(11) NOT NULL,"
                    + "latitude FLOAT(10,6) NOT NULL,"
                    + "longitude FLOAT(10,6) NOT NULL,"
                    + "created_at DATETIME NOT NULL )");

insert_into_table method:

private void insert_into_table(String macD, int routeD, double latD,
        double longD, Connection con) throws SQLException {

    Calendar calendar = new GregorianCalendar();
    TimeZone timeZone = TimeZone.getTimeZone("Europe/Berlin");
    calendar.setTimeZone(timeZone);
    String time = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss")
            .format(calendar.getTime());

    PreparedStatement prep = con
            .prepareStatement("REPLACE INTO bus(mac, route, latitude, longitude, created_at)"
                    + "VALUES( ?, ?, ? , ?,? )");
    prep.setString(1, macD);
    prep.setInt(2, routeD);
    prep.setDouble(3, latD);
    prep.setDouble(4, longD);
    prep.setString(5, time);
    prep.executeQuery();
}

Clearly, the default date/time format on your application computer is not recognized on the MySQL server. The easiest fix is to use the database for setting the time.

One way is:

PreparedStatement prep = con
         .prepareStatement("REPLACE INTO bus(mac, route, latitude, longitude, created_at)"
                 + "VALUES( ?, ?, ? , ?, now())");

A better way is to define created_at so it has a default value of the insertion time. Then you can leave it out of the replace / insert altogether. This process is explained here. Some details depend on the version of MySQL that you are using.

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