简体   繁体   English

MySQL中的Where子句-JAVA

[英]Where Clause in MySQL - JAVA

I'm newbie with mysql and this is my issue. 我是mysql的新手,这是我的问题。 I have a table in database called Room with one of its attribute as Floor. 我在数据库中有一个名为Room的表,其属性之一为Floor。 In the Floor column, there are 3 different names ( Walters, Gates, Pension). 在“楼层”列中,有3个不同的名称(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. 这似乎是正确的查询,但我在where子句中说Unknown Column'Walters'时抛出错误。

What am i not doing right? 我做错了吗?

Your query is not correct, because String should be between to quotes "" : 您的查询不正确,因为String应该在引号""之间:

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 : 但这并不安全,而是阅读有关Prepared Statement的内容,以避免SQL Injection和语法错误:

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 最好使用PreparedStatements以避免混淆

用这个,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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