1

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.

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Shouldn't you enclose TimeStamp variable in simple quotes?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.