Search code examples
javasqlderby

Java PreparedStatement syntax issues


I'm having some issues with SQL syntax errors when using Java PreparedStatements.

The three statements I'm trying to prepare are as follows:

insertBook = con.prepareStatement("INSERT INTO Books ? VALUES ?");
selectBooks = con.prepareStatement("SELECT * FROM Books?");
deleteBooks = con.prepareStatement("DELETE FROM Books?");

In the first statement, I'd like to pass in two strings, one containing a list of columns to insert into, and the other containing all the values to insert. In the other two statements, I'd like to insert an (optional) WHERE clause at the end.

I've already seen this question which appears to deal with a similar issue, but in his case it appeared that he was trying to use the ?s where it didn't make sense; unless I've failed at SQL, I can't see any reason why I shouldn't be able to insert my strings here. I've scoured the Javadocs, but can't seem to come up with an explanation there, either.

Many thanks!


Solution

  • That is how it was designed. ?-s left for only parameters, Consider to use StringBuilder to concatenate your 'WHERE' clauses.

    This is just a simple case u may not use StringBuilder here, it is effective for building complex queries

    Here is your example

    String whereClause = " WHERE Id = ?";
    
    String insert = "INSERT INTO [Table](C1, C2) VALUES(?, ?)";
    String select = "SELECT * FROM [Table] ";
    String update = "UPDATE [Table] SET C1 = ? ";
    String delete = "DELETE FROM [Table] ";
    
    PreparedStatement insertSt = con.prepareStatement(insert);
    PreparedStatement selectSt = con.prepareStatement(select + whereClause);
    PreparedStatement deleteSt = con.prepareStatement(update + whereClause);
    PreparedStatement updateSt = con.prepareStatement(delete + whereClause);