0

我无法正确插入 TIMESTAMP 字段。

方法如下所示:

private static void addPickup(Connection conn, boolean debug, String 
        logfileName, String serverName, String mapName, long start, 
        long end) throws SQLException {

    try (CallableStatement statement = conn.prepareCall("{CALL AddPickup "
                 + "(?, ?, ?, ?, ?) }")) {
        statement.setString(1, logfileName);
        statement.setString(2, serverName);
        statement.setString(3, mapName);
        statement.setTimestamp(4, new Timestamp(start));
        statement.setTimestamp(5, new Timestamp(end));
        statement.execute();
    }
}

start 的值为 1373573918000

end 的值为 1373574819000

程序:

CREATE PROCEDURE AddPickup(
    IN logfilename VARCHAR(45), 
    IN servername VARCHAR(10), 
    IN mapname VARCHAR(20),
    IN start TIMESTAMP,
    IN end TIMESTAMP
)
AddPickup:BEGIN
IF EXISTS(SELECT p.id FROM pickup p WHERE p.logfile_name = logfilename) THEN
    LEAVE AddPickup;
END IF;

INSERT IGNORE INTO map (name) VALUES (mapname);
INSERT IGNORE INTO server (name) VALUES (servername);
INSERT INTO pickup (logfile_name, server_id, map_id, started, ended, datetime) 
    VALUES (
        logfilename, 
        (SELECT s.id FROM server s WHERE s.name = servername),
        (SELECT m.id FROM map m WHERE m.name = mapname),
        start,
        end,
        NOW()
    );
END //

表:

CREATE TABLE map (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(20) UNIQUE NOT NULL
) ENGINE = 'InnoDB';

CREATE TABLE server (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(10) UNIQUE NOT NULL
) ENGINE = 'InnoDB';

CREATE TABLE pickup (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    logfile_name VARCHAR(45) UNIQUE NOT NULL,
    server_id INT UNSIGNED NOT NULL,
    map_id INT UNSIGNED NOT NULL,
    started TIMESTAMP NOT NULL,
    ended TIMESTAMP NOT NULL,
    datetime DATETIME NOT NULL,
    FOREIGN KEY (map_id) REFERENCES map(id) ON UPDATE CASCADE ON DELETE CASCADE,
    FOREIGN KEY (server_id) REFERENCES server(id) ON UPDATE CASCADE ON DELETE CASCADE
 ) ENGINE = 'InnoDB';

它按应有的方式将所有内容插入表中,只是两个TIMESTAMP字段pickup.startedpickup.ended总是显示“0000-00-00 00:00:00”,我不知道为什么。

4

2 回答 2

0

我认为问题在于您传递给setTimestamp的参数

当我使用setTimestamp时,如果我没有具体的使用日期,我总是传递一个new Date().getTime()作为参数。

private static void addPickup(Connection conn, boolean debug, String 
    logfileName, String serverName, String mapName, long start, 
    long end) throws SQLException {

try (CallableStatement statement = conn.prepareCall("{CALL AddPickup "
             + "(?, ?, ?, ?, ?) }")) {
    statement.setString(1, logfileName);
    statement.setString(2, serverName);
    statement.setString(3, mapName);
    statement.setTimestamp(4, new Date().getTime());
    statement.setTimestamp(5, new Date().getTime());
    statement.execute();
}

}

于 2013-07-23T12:47:32.663 回答
0

我不太确定它在 MYSQL 中是如何工作的,但是当我在 SQLSERVER 中使用时间戳时,TIMESTAMP 用于在创建行时自动生成,在这种情况下,我没有为时间戳提供任何值询问。所以只需尝试 n 插入其他值希望它也可以帮助你。

于 2013-08-14T10:47:27.013 回答