2012-12-16 30 views
-2

我真的建立針對不同客戶的數據庫,他們有自己的用戶名和密碼,但我想看到的時候,當他們登錄即時通訊使用下面的代碼:插入時間到MySQL和Java

if (userName.equals("EXAMPLE")) { 


         Calendar cal = Calendar.getInstance(); 
         cal.getTime(); 
         SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
         String Time = "update `clients` set `time`= 
          "+ sdf.format(cal.getTime()) + " where clientid=1 "; 

但有些事情是錯的,它不會更新表格。 我真的很感激你的幫助。 另外,作爲一個額外的問題,這將是很好,如果你能幫助我更新不僅時間,但日期以及。 謝謝謝謝你的時間。

回答

1

我想出了答案。

public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; 

public static String now() { 
    Calendar cal = Calendar.getInstance(); 
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); 
    return sdf.format(cal.getTime()); 
      } 

,然後現在要求()時necessery:

if (userName.equals("EXAMPLE")) { 


         //update time when client logged in 
         String Time = "update `clients` set `time`='" + now() + "' where clientid=1 "; 
         stmt.executeUpdate(Time); 

      } 
0

你只是缺乏圍繞價值

String Time = "update `clients` set `time`= 
         '" + sdf.format(cal.getTime()) + "' where clientid=1 "; 

單引號,但要記住,這個弱勢與SQL Injection,通過使用PreparedStatements

參數化查詢
String Time = "update `clients` set `time`= ? where clientid=1 "; 
PreparedStatement pstmt = con.prepareStatement(Time); 
pstmt.setDate(1, cal.getTime()); 
pstmt.executeUpdate();