Query中的字符串参数

时间:2013-01-17 07:43:06

标签: java mysql groovy

我是程序员学习者。

我希望以下列格式获取MySQL查询

 select status from training where status in ("Open", "Delivered")

来自我的代码

if(params.openCheckBox){
    query +=" ( t.status  IN ("+params.openCheckBox+", "+params.DeliveredCheckBox+")" 
    query +=" )"
}

但它给出了

   select status from training where status in (Open, Delivered)

这里“”(缺少双引号)

2 个答案:

答案 0 :(得分:4)

使用\转义双引号,MySQL接受双引号来换行。

query +=" ( t.status  IN (\""+params.openCheckBox+"\", \""+params.DeliveredCheckBox+"\")" 
query +=" )"

或 只使用单引号

query +=" ( t.status  IN ('"+params.openCheckBox+"', '"+params.DeliveredCheckBox+"')" 
query +=" )"

上面的查询容易被sql injection攻击。使用PreparedStatement,如下面的那个

代码段:

dbConnection = getDBConnection();
String query = "SELECT .... FROM .... WHERE t.status IN (?, ?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setString(1, params.openCheckBox);
preparedStatement.setString(2, params.DeliveredCheckBox);
ResultSet rs = preparedStatement.executeQuery();

SOURCES

答案 1 :(得分:1)

您可以改用单引号。

query +=" ( t.status  IN ('"+params.openCheckBox+"', '"+params.DeliveredCheckBox+"')"