简体   繁体   中英

Where Clause in MySQL - JAVA

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?

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

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

用这个,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM