i am trying to insert timestamp
to my database but i keep getting java.sql.SQLSyntaxErrorException
:
here is my code
java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
System.out.println(sqlDate);
Here the insertion and connection to 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);
}
Error
2017-04-09 20:10:02.825 Connection failed adding vote java.sql.SQLSyntaxErrorException: Syntax error: Encountered "20" at line 1, column 94.
You should to put your time between ''
like this :
"VALUES ('" + Candidate_Name + "','" + ssn + "', ' " + TimeStamp + "')";
But this is not secure enough, you have to use PreparedStatement instead to avoid any SQL Injection.
For example :
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();
}