Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 299
Chase Avatar asked Dec 04 '25 15:12

Chase


1 Answers

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());
}
like image 135
tstr Avatar answered Dec 07 '25 05:12

tstr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!