0

This query retrieves the correct value when run in MySQL workbench.

select person_id from person where person_name='John Adam';

But when I run it from by Java code, it gives the exception at the line in which executeQuery() is called.

SQLState: 42S22
Error Code: 1054
Message: Unknown column 'John Adam' in 'where clause'

My code is:

String inputname= JOptionPane.showInputDialog ( "Enter person's name:" ); 
String query= "select person_id from person where person_name= "+ inputname;

try {
    stmt=con.createStatement();
    ResultSet rs = stmt.executeQuery(query); // EXCEPTION AT THIS LINE
    while (rs.next()){
    rid= rs.getInt("person_id");
    } // .....

What do you think can be the reason for this?

2 Answers 2

4

You need to put quotes around your input

String query= "select person_id from person " + 
              "where person_name= '"+ inputname + "'";

Or better use Prepared Statements to let the escaping do the program for you automatically.

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

Comments

1

Try with single quotes

String query= "select person_id" + 
               "from person where person_name= '"+ inputname+"'";

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.