如何在PreparedStatement中使用多个可选参数填充查询sql? [英] How to fill a query sql with multiple optional parameter in PreparedStatement?
问题描述
我自己解释......
I explain myself...
我有一个填写查询的表格(例如):
I have a form with fill the query (eg.):
SELECT *
FROM table
WHERE id=? AND name=? AND sex=? AND year=? AND class=?
但只有id是必需的,所有其他参数都是可选的。
如何填写(或重新创建)该查询的prerared语句???
but only the "id" is mandatory, all the other parameter are optional. How can I fill (or re-create) the prerared statement for that query ???
推荐答案
你' d要么必须使用多个预准备语句,要么只是动态创建一个语句,检查你有哪些参数。
You'd either have to use multiple prepared statements or just create a statement on the fly, checking which parameters you have.
像这样:
String query = "SELECT * FROM table WHERE id=?";
if( nameParameter != null ) {
query += " AND name=?"; //don't never ever directly add the value here
}
...
更新/警告:不要直接将参数值添加到查询字符串中,而是使用 PreparedStatement
等。如上所示,查询字符串应该只包含值的占位符(例如?
),以防止SQL注入攻击。
Update/Warning: Don't directly add the parameter values to the query string but use PreparedStatement
and the like instead. As displayed above the query string should only contain placeholders for the values (eg. ?
) in order to prevent SQL-injection attacks.
我的意思是, 不要执行以下操作 :
What I mean is, do NOT do the following:
if( nameParameter != null ) {
//NEVER EVER, REALLY I MEAN IT, DON'T DO THIS
query += " AND name='" + nameParameter + "'";
}
这篇关于如何在PreparedStatement中使用多个可选参数填充查询sql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!