0

I'm using JDBC for the first time and having a tough time at it. This is a code snippet that is giving me error:

//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql;
sql = "SELECT * FROM user where username=? and password=?";
stmt = conn.prepareStatement(sql);
//Bind values into the parameters.
stmt.setString(1, value1);  // This would set username
stmt.setString(2, value2); // This would set password
ResultSet rs = stmt.executeQuery(sql);

I'm getting the following error in NetBeans:

"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 '? and password=?' at line 1"

There is a long list after this but I think this is the thing which is causing me problems. What am I doing wrong?

1 Answer 1

3

You already have set the SQL for the statement and the parameters are bound.

Hence, you need not set the SQL again for the same statement. Otherwise it is an invalid statement and and exception is thrown.

Change:

ResultSet rs = stmt.executeQuery(sql);

To:

ResultSet rs = stmt.executeQuery();
Sign up to request clarification or add additional context in comments.

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.