2013-07-20 66 views
0

我遇到了麻煩,無法正確插入TIMESTAMP字段。Java JDBC插入到TIMESTAMP類型中的MySQL失敗

方法看起來像這樣:

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

開始具有值1373573918000

端具有值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「,我不明白爲什麼。

回答

0

我認爲這個問題是在傳遞給的setTimestamp

參數當我使用的setTimestamp,如果我不得不使用不具體日期,我一直在傳遞一個新的日期( ).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(); 
} 

}

0

我不是很肯定的東西它是如何工作的MYSQL,但是當我是在SQLSERVER時間戳工作,使用的TIMESTAMP自動生成每當行創建,在那種情況下,我沒有提供任何查詢時間戳的值。所以只需嘗試n插入其他值 希望它也可以幫助你。