0

I am writing the following SQL query in my Java program

PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from "                 
    + "student where ID =" + ID + " or FirstName=" + firstName + ";");

However, I am getting the following error:

use the right syntax for FirstName="+Parker

How is this caused and how can I solve it?

1
  • Please give the exact error, as well as telling us what the database is, and whether you're getting the error at compile-time or execution time. Commented Nov 9, 2012 at 23:32

3 Answers 3

1

You should take advantage of prepared statements by making use of prepared statements parameters. This way, you can set your parameters pragmatically using setters.

http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.

Here is a snippet from the Oracle docs:

PreparedStatement updateSales = null;

String updateString = "update " + dbName + ".COFFEES " + "set SALES = ? where COF_NAME = ?";

updateSales = con.prepareStatement(updateString);

updateSales.**setInt**(1, e.getValue().intValue());

updateSales.**setString**(2, e.getKey());

Just make sure you set the statements *in order a*s the sql query.

Sign up to request clarification or add additional context in comments.

1 Comment

Let me ask, the way my prepared statement is written right now, is there any syntax error in that statement? When I debug my program, the variable firstName contains a value(which is Parker) but I wonder why it tells me that there is syntax error. Its hard to get the actual error because I can see it when I hover over my PrintStackTrace object.But it basically says " check the manual that corresponds with it, sql error near FirstName="+Parker
1

Use a PreparedStatement like this:

PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from student where ID = ? or FirstName = ?");
pre.setInt(1, ID);
pre.setString(2, firstName);

Comments

0

I haven't used sql in Java, but my guess is it is because you don't have single quotes around first name. You want:

PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from " + "student where ID =" + ID + " or FirstName='" + firstName + "';");

emphasis:

... FirstName='" + firstName + "';");

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.