3

I'm newbie with mysql and this is my issue. I have a table in database called Room with one of its attribute as Floor. In the Floor column, there are 3 different names ( Walters, Gates, Pension).

I'm trying to fetch figures from table based on the selected floor and this is my query.

 String query = "Select * from Rooms where Floor =" + Floor.getSelectedItem().toString();

This seems like the right query but i get an error thrown saying Unknown Column 'Walters' in where clause.

What am i not doing right?

2

3 Answers 3

4

Your query is not correct, because String should be between to quotes "" :

String query = 
     "Select * from Rooms where Floor = '" + Floor.getSelectedItem().toString() + "'";
    //----------------------------------^------------------------------------------^

But this not secure, instead read about Prepared Statement to avoid SQL Injection and syntax error :

String query = "Select * from Rooms where Floor = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, Floor.getSelectedItem().toString());
pstmt.executeQuery();//then execute the statement
Sign up to request clarification or add additional context in comments.

Comments

1

strings in a query should be in single quotes, your query should be:

Select * from Rooms where Floor = 'Walter';

so your code should be:

String query = "Select * from Rooms where Floor = '" + Floor.getSelectedItem().toString() + "'";

It is better to use PreparedStatements to avoid confusion

Comments

0

Use this,

String query = "Select * from Rooms where Floor ='" + Floor.getSelectedItem().toString();+"'"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.