2011-11-24 57 views
0

每個機構。我收到此錯誤: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '14:37:41)' at line 1 對於這段代碼Java到MySql的日期DateTime

 public String addName() { 
    // TODO Auto-generated method stub 
    try { 
     java.util.Date dt = new java.util.Date(); 
     java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
       "yyyy-MM-dd HH:mm:ss"); 

     String currentTime = sdf.format(dt); 



     String name = "RandomName"; 

     Connection connect = DriverManager.getConnection(
       "jdbc:mysql://localhost", "ericman", "ericman"); 
     Statement stat = (Statement) connect.createStatement(); 
     String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES ('" 
       + name + "', " + currentTime + ")"; 
     stat.executeUpdate(insert); 

    } catch (Exception e) { 
     System.out.println(e); 
    } 
    return "Name Updated"; 
} 

爲什麼出現這種情況,我吮吸結構化語言的任何建議,只是讓你知道:)

+0

將日期插入到字符串中是錯誤的... – Michael

回答

5

使用PreparedStatement

String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES (?,?)"; 
PreparedStatement ps=connect.prepareStatement(insert); 
ps.setString(1,name); 
ps.setTimeStamp(2,TimeStamp.valueOf(currentTime)); 
ps.executeUpdate(); 
+0

確定已修復它!!!!!非常感謝! – helloThere

3

你缺少你周圍currentTime的'字符插入語句。

但是,您確實應該使用準備好的語句來防止SQL注入攻擊。

1

您是否需要用逗號將您的日期/時間封裝在INSERT語句中,就像使用名稱參數一樣?

1

呃。爲什麼不使用PreparedStatement呢?

PreparedStatement stmt = connect.prepareStatement("INSERT INTO bookcatalog.puch(name, time) values ?,?"); 
stmt.setString(1, name); 
stmt.setTimestamp(2, dt); 
stmt.execute(); 

它更清潔。

+0

我在MySQL語言中很糟糕。你能否證明,你的代碼將如何取代我的錯誤代碼?謝謝!! – helloThere

+0

查看上面通過@AVD鏈接的示例。 – mcfinnigan

+0

它說,我應該施加時間戳,所以我做到了。我不能看到任何鏈接既不是AVD用戶?謝謝! – helloThere