MySQL中的条款 - JAVA

时间:2017-09-10 07:56:14

标签: java mysql jdbc

我是mysql的新手,这是我的问题。我在数据库中有一个名为Room的表,其中一个属性为Floor。在“楼层”列中,有3个不同的名称(Walters,Gates,Pension)。

我试图根据所选楼层从表中获取数据,这是我的查询。

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

这看起来像是正确的查询,但我得到一个错误抛出说未知列' Walters'在where子句中。

我做得不对?

3 个答案:

答案 0 :(得分:3)

您的查询不正确,因为字符串应位于引号""之间:

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

但这不安全,而是阅读Prepared Statement以避免SQL注入和语法错误:

String query = "Select * from Rooms where Floor = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, Floor.getSelectedItem().toString());
pstmt.executeQuery();//then execute the statement

答案 1 :(得分:1)

查询中的

字符串应该是单引号,您的查询应该是:

Select * from Rooms where Floor = 'Walter';

所以你的代码应该是:

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

最好使用PreparedStatements来避免混淆

答案 2 :(得分:0)

使用此,

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