2017-04-09 82 views
1

我試圖插入timestamp到我的數據庫,但我不斷收到java.sql.SQLSyntaxErrorException的Java SQL插入時間戳java.sql.SQLSyntaxErrorException

這裏是我的代碼

java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime()); 
System.out.println(sqlDate); 

這裏插入並連接到DB

Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1598/VotingDB", "app", "app"); 
    Statement st = conn.createStatement(); 
    String sql = "INSERT INTO VOTES (CANDIDATE_NAME,VOTER_SSN,TIMESTAMP) " 
      + "VALUES ('" + Candidate_Name + "','" + ssn + "'," + TimeStamp + ")"; 

    st.executeUpdate(sql); 
    st.close(); 
    conn.close(); 
} catch (SQLException ex) { 
    System.out.println("Connection failed adding vote " + ex); 
} 

錯誤

2017-04-09 20:10:02.825 Connection failed adding vote java.sql.SQLSyntaxErrorException: Syntax error: Encountered "20" at line 1, column 94.

回答

2

你應該把你的時間''之間是這樣的:

"VALUES ('" + Candidate_Name + "','" + ssn + "', ' " + TimeStamp + "')"; 

但這是不夠安全,你必須在使用PreparedStatement代替,以避免任何SQL注入。

例如:

String sql = "INSERT INTO VOTES (CANDIDATE_NAME, VOTER_SSN, TIMESTAMP) VALUES (?, ?, ?)"; 

try (PreparedStatement stm = connection.prepareStatement(sql)) { 

    stm.setString(1, Candidate_Name); 
    stm.setString(2, ssn); 
    stm.setDate(3, TimeStamp); 

    stm.executeUpdate(); 
} 
1

難道你不應該用簡單的引號括起TimeStamp變量嗎?

String sql = "INSERT INTO VOTES (CANDIDATE_NAME,VOTER_SSN,TIMESTAMP) " 
    + "VALUES ('"+Candidate_Name +"','"+ssn +"','"+TimeStamp+"')";