0
try
         {
            String sql="INSERT INTO `task`(`task`,`time`) VALUES(?,?)";
            PreparedStatement stmt=this.connection.prepareStatement(sql);
            stmt.setString(1, this.task);
            stmt.setInt(2, this.time);
            //stmt.
            Boolean res= stmt.execute(sql);
         }
         catch(Exception e)
         {
             System.err.println(e);
         }

ERROR:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1

1 Answer 1

2

Don't use

stmt.execute(sql);

use

stmt.execute();

to execute your PreparedStatement.

The first one you are using tries to execute the given string, which is obviously not what you want to execute due to the placeholder '?' values in it (it is a method of the java.sql.Statement interface).

The second one is a method from java.sql.PreparedStatement and executes the PreparedStatement with the values you entered through the setXXX() methods.


Also, in your case you don't need ticks in your string, you can just write

String sql="INSERT INTO task(task,time) VALUES(?,?)";
Sign up to request clarification or add additional context in comments.

8 Comments

MySql expects for String 'value' not value, so try to put ? into quotes.
@JevgeniSmirnov: No, don't need it, PreparedStatement takes care of that for you.
@jlordo With JDBC you could also need backticks, but only where it is actually required (just like with all other MySQL uses, see dev.mysql.com/doc/refman/5.5/en/identifiers.html).
@jlordo, oh ok. Will put a note to myself.
@MarkRotteveel should we always use backticks then in the query String, or only if it is a reserved word (eg: event)?
|

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.