为什么我会收到 "com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value:" 错误?

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

我正在尝试将 OPENSHIFT 上 table 中的 created_at 列时间 created_at DATETIME NOT NULL 设置为我的当地时间 Kopenhagen。如何将 openshift 服务器中的时间设置为本地时间?目前我在这一行 prep.executeQuery();

收到此错误 com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '16.05.2015 22:28:13' for column 'created_at' at row 1

感谢任何帮助。

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方法:

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();
}

显然,MySQL 服务器无法识别应用程序计算机上的默认 date/time 格式。最简单的解决方法是使用数据库来设置时间。

一种方法是:

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

更好的方法是定义created_at,使其具有插入时间的默认值。然后你可以将它完全排除在 replace/insert 之外。这个 process 在这里解释。一些细节取决于您使用的 MySQL 版本。