简体   繁体   中英

Prepared Statement with Null Parameters

I'm working on a little Database Program witch make easy Select querys.

The Program use a GUI where you can enter the search parameters. If you don't enter all Parameters they will be Completed by the results of the query. So i tried to Check wether the Parameter from the Textbox is empty/null and set the Placeholder to "*".

But when i tried to run. Even with programmed Placeholders it give me an SQLException Syntax Error.

I will post a shortend Version of the Whole Code witch technaly is the Same.

PreparedStatement Statement = connection.prepareStatement("select * From t_person where user_a = ? "+ "AND where dasatz_a = ? " + "AND where user_g = ? ");

if (Parameter.get(0) == null) {
    Parameter.set(0, "*") };

Statement.setString(1, Parameter.get(0));

and so on.

Parameter is an ArrayList With the Parameters from the Textboxes.

Simply don't filter the column in any way if there is no parameter specified for "filtered" column. Dynamically prepare your query to inlude only parameters which are specified.

Map<Integer, String> statementParams = new HashMap<>();
String query = "select * From t_person";
boolean firstCondition = true;

if (Parameter.get(0) != null) {
    if (firstCondition) {
        query += " where ";
        firstCondition = false;
    } else {
        query += " and ";
    }
    query += "user_a = ?";
    statementParams.put(1, Parameter.get(0));
}
// other params
PreparedStatement Statement = connection.prepareStatement(query);

for (MapEntry<Integer, String> entry : statementParams.entrySet()) {
    Statement.setString(entry.getKey(), entry.getValue());
}

As @juergen d pointed out, your sql statement is invalid because it has multiple where clauses in it:

select * From t_person where user_a = ? "+ "AND where dasatz_a = ? " + "AND where user_g = ?

should be:

select * From t_person where user_a = ? AND dasatz_a = ? AND user_g = ?

Additionally, your use of '*' will result in values where user_a is literally * . If you are wanting to make it a wildcard search, the syntax must change to be LIKE (instead of equals) and use '%' rather than '*' .

http://www.w3schools.com/sql/sql_wildcards.asp

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