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?

Ravinder Reddy
24.1k6 gold badges54 silver badges86 bronze badges
asked Jun 7, 2014 at 17:36

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();
answered Jun 7, 2014 at 17:40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.