How to remove a condition from where clause, if specific value is null (using prepared statements)












0















Getting parameters from request:



String city = request.getParameter("city");
int price = Integer.parseInt(request.getParameter("price").toString());
int guests ... etc
date init_date... etc
date end_date...etc
initDate = parse init_date with simpledateformater...etc
endDate = parse init_date with simpledateformater...etc


Lets have a prepared statemente like this:



String getResult = "SELECT id_housing, name, description_short, price, 
photo FROM housing WHERE city = ? AND init_date <= ? AND end_date >= ? AND
price = ? AND guests >= ?";

PreparedStatement stmt = con.prepareStatement(getResult);

stmt.setString(1, city);
stmt.setDate(2, new java.sql.Date(initDate.getTime()));
stmt.setDate(3, new java.sql.Date(endDate.getTime()));
stmt.setInt(4, price);
stmt.setInt(5, guests);
ResultSet rs = stmt.executeQuery();


The question is how can I remove city or price or any value after the WHERE clause, if the value is null.
For example, if my user dooesnt write any text on the city input text, the request.getParameter is gonna be null (or an empty string "", i dont know). In that case, I want to remove the city = ? condition from the prepared statement, so the query will return rows with any city value).



I tried with



WHERE city = IFNULL(? , *) AND ...


But doesnt work.










share|improve this question























  • One option is just to construct your getResult based on some conditions, so, for example, if city == null just don't add it to the query at all. Another, use one of the sql query builder java libs. Take a look at this for example stackoverflow.com/questions/15405288/…

    – Sergei Sirik
    Nov 14 '18 at 23:26











  • Possible duplicate of Prepared statement with dynamic where clause

    – Sergei Sirik
    Nov 14 '18 at 23:27
















0















Getting parameters from request:



String city = request.getParameter("city");
int price = Integer.parseInt(request.getParameter("price").toString());
int guests ... etc
date init_date... etc
date end_date...etc
initDate = parse init_date with simpledateformater...etc
endDate = parse init_date with simpledateformater...etc


Lets have a prepared statemente like this:



String getResult = "SELECT id_housing, name, description_short, price, 
photo FROM housing WHERE city = ? AND init_date <= ? AND end_date >= ? AND
price = ? AND guests >= ?";

PreparedStatement stmt = con.prepareStatement(getResult);

stmt.setString(1, city);
stmt.setDate(2, new java.sql.Date(initDate.getTime()));
stmt.setDate(3, new java.sql.Date(endDate.getTime()));
stmt.setInt(4, price);
stmt.setInt(5, guests);
ResultSet rs = stmt.executeQuery();


The question is how can I remove city or price or any value after the WHERE clause, if the value is null.
For example, if my user dooesnt write any text on the city input text, the request.getParameter is gonna be null (or an empty string "", i dont know). In that case, I want to remove the city = ? condition from the prepared statement, so the query will return rows with any city value).



I tried with



WHERE city = IFNULL(? , *) AND ...


But doesnt work.










share|improve this question























  • One option is just to construct your getResult based on some conditions, so, for example, if city == null just don't add it to the query at all. Another, use one of the sql query builder java libs. Take a look at this for example stackoverflow.com/questions/15405288/…

    – Sergei Sirik
    Nov 14 '18 at 23:26











  • Possible duplicate of Prepared statement with dynamic where clause

    – Sergei Sirik
    Nov 14 '18 at 23:27














0












0








0








Getting parameters from request:



String city = request.getParameter("city");
int price = Integer.parseInt(request.getParameter("price").toString());
int guests ... etc
date init_date... etc
date end_date...etc
initDate = parse init_date with simpledateformater...etc
endDate = parse init_date with simpledateformater...etc


Lets have a prepared statemente like this:



String getResult = "SELECT id_housing, name, description_short, price, 
photo FROM housing WHERE city = ? AND init_date <= ? AND end_date >= ? AND
price = ? AND guests >= ?";

PreparedStatement stmt = con.prepareStatement(getResult);

stmt.setString(1, city);
stmt.setDate(2, new java.sql.Date(initDate.getTime()));
stmt.setDate(3, new java.sql.Date(endDate.getTime()));
stmt.setInt(4, price);
stmt.setInt(5, guests);
ResultSet rs = stmt.executeQuery();


The question is how can I remove city or price or any value after the WHERE clause, if the value is null.
For example, if my user dooesnt write any text on the city input text, the request.getParameter is gonna be null (or an empty string "", i dont know). In that case, I want to remove the city = ? condition from the prepared statement, so the query will return rows with any city value).



I tried with



WHERE city = IFNULL(? , *) AND ...


But doesnt work.










share|improve this question














Getting parameters from request:



String city = request.getParameter("city");
int price = Integer.parseInt(request.getParameter("price").toString());
int guests ... etc
date init_date... etc
date end_date...etc
initDate = parse init_date with simpledateformater...etc
endDate = parse init_date with simpledateformater...etc


Lets have a prepared statemente like this:



String getResult = "SELECT id_housing, name, description_short, price, 
photo FROM housing WHERE city = ? AND init_date <= ? AND end_date >= ? AND
price = ? AND guests >= ?";

PreparedStatement stmt = con.prepareStatement(getResult);

stmt.setString(1, city);
stmt.setDate(2, new java.sql.Date(initDate.getTime()));
stmt.setDate(3, new java.sql.Date(endDate.getTime()));
stmt.setInt(4, price);
stmt.setInt(5, guests);
ResultSet rs = stmt.executeQuery();


The question is how can I remove city or price or any value after the WHERE clause, if the value is null.
For example, if my user dooesnt write any text on the city input text, the request.getParameter is gonna be null (or an empty string "", i dont know). In that case, I want to remove the city = ? condition from the prepared statement, so the query will return rows with any city value).



I tried with



WHERE city = IFNULL(? , *) AND ...


But doesnt work.







java mysql servlets prepared-statement






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 23:13









Keka BronKeka Bron

10610




10610













  • One option is just to construct your getResult based on some conditions, so, for example, if city == null just don't add it to the query at all. Another, use one of the sql query builder java libs. Take a look at this for example stackoverflow.com/questions/15405288/…

    – Sergei Sirik
    Nov 14 '18 at 23:26











  • Possible duplicate of Prepared statement with dynamic where clause

    – Sergei Sirik
    Nov 14 '18 at 23:27



















  • One option is just to construct your getResult based on some conditions, so, for example, if city == null just don't add it to the query at all. Another, use one of the sql query builder java libs. Take a look at this for example stackoverflow.com/questions/15405288/…

    – Sergei Sirik
    Nov 14 '18 at 23:26











  • Possible duplicate of Prepared statement with dynamic where clause

    – Sergei Sirik
    Nov 14 '18 at 23:27

















One option is just to construct your getResult based on some conditions, so, for example, if city == null just don't add it to the query at all. Another, use one of the sql query builder java libs. Take a look at this for example stackoverflow.com/questions/15405288/…

– Sergei Sirik
Nov 14 '18 at 23:26





One option is just to construct your getResult based on some conditions, so, for example, if city == null just don't add it to the query at all. Another, use one of the sql query builder java libs. Take a look at this for example stackoverflow.com/questions/15405288/…

– Sergei Sirik
Nov 14 '18 at 23:26













Possible duplicate of Prepared statement with dynamic where clause

– Sergei Sirik
Nov 14 '18 at 23:27





Possible duplicate of Prepared statement with dynamic where clause

– Sergei Sirik
Nov 14 '18 at 23:27












4 Answers
4






active

oldest

votes


















0














Just change the getResult String when the city value is null. Something like this:



if(city == null) {
getResult = "SELECT id_housing, name, description_short, price, photo FROM housing AND init_date <= ? AND end_date >= ? AND price = ? AND guests >= ?";





share|improve this answer































    0














    String getResult = "SELECT id_housing, name, description_short, price, 
    photo FROM housing WHERE init_date <= ? AND end_date >= ? AND
    price = ? AND guests >= ?";
    if(city != null && !city.isempty()){
    getResult += " AND city = ? "
    }

    PreparedStatement stmt = con.prepareStatement(getResult);
    if(city != null && !city.isempty()){
    stmt.setString(1, city);
    }





    share|improve this answer

































      0














      One way to achieve this is to have a query stub/template into which you dynamically append the WHERE condition. You keep the bind variables in a map which maps the variable index into the corresponding value:



      String queryStub = "SELECT id_housing, name, description_short, price, " 
      + "photo FROM housing WHERE 1=1";

      Map<Integer, Object> bindVariables = new HashMap<>();
      StringBuilder sb = new StringBuilder(queryStub);
      int paramIndex = 1;

      if (city != null && !city.isEmpty()) {
      sb.append(" AND city = ?")
      bindVariables.put(paramIndex++, city);
      }

      // ... handle the other, possibly empty inputs

      try (PreparedStatement stmt = con.prepareStatement(sb.toString());) {

      for (Map.Entry<Integer, Object> e : bindVariables.entrySet()) {
      stmt.setObject(e.getKey(), e.getValue());
      }

      ResultSet rs = stmt.executeQuery();
      // ...
      }





      share|improve this answer

































        -1














        Unfortunately. you need a separate query for this case.



        This is one reasons it's often not a good idea to use raw JDBC to access a database. With complex queries, you end up with a bunch of error-prone logic that builds pieces and concatenates them.
        If you don't have many of these cases, then just use two different queries.



        But if you keep running into more of these queries, then there are plenty of libraries that can help with everything from opening connections to safely executing queries without having to build different queries using raw strings. Jooq and mybatis come to mind.






        share|improve this answer


























        • he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

          – Justin
          Nov 14 '18 at 23:36











        • @Justin You're right.

          – Malt
          Nov 14 '18 at 23:40











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310162%2fhow-to-remove-a-condition-from-where-clause-if-specific-value-is-null-using-pr%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Just change the getResult String when the city value is null. Something like this:



        if(city == null) {
        getResult = "SELECT id_housing, name, description_short, price, photo FROM housing AND init_date <= ? AND end_date >= ? AND price = ? AND guests >= ?";





        share|improve this answer




























          0














          Just change the getResult String when the city value is null. Something like this:



          if(city == null) {
          getResult = "SELECT id_housing, name, description_short, price, photo FROM housing AND init_date <= ? AND end_date >= ? AND price = ? AND guests >= ?";





          share|improve this answer


























            0












            0








            0







            Just change the getResult String when the city value is null. Something like this:



            if(city == null) {
            getResult = "SELECT id_housing, name, description_short, price, photo FROM housing AND init_date <= ? AND end_date >= ? AND price = ? AND guests >= ?";





            share|improve this answer













            Just change the getResult String when the city value is null. Something like this:



            if(city == null) {
            getResult = "SELECT id_housing, name, description_short, price, photo FROM housing AND init_date <= ? AND end_date >= ? AND price = ? AND guests >= ?";






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 14 '18 at 23:25









            Naeem KhanNaeem Khan

            699




            699

























                0














                String getResult = "SELECT id_housing, name, description_short, price, 
                photo FROM housing WHERE init_date <= ? AND end_date >= ? AND
                price = ? AND guests >= ?";
                if(city != null && !city.isempty()){
                getResult += " AND city = ? "
                }

                PreparedStatement stmt = con.prepareStatement(getResult);
                if(city != null && !city.isempty()){
                stmt.setString(1, city);
                }





                share|improve this answer






























                  0














                  String getResult = "SELECT id_housing, name, description_short, price, 
                  photo FROM housing WHERE init_date <= ? AND end_date >= ? AND
                  price = ? AND guests >= ?";
                  if(city != null && !city.isempty()){
                  getResult += " AND city = ? "
                  }

                  PreparedStatement stmt = con.prepareStatement(getResult);
                  if(city != null && !city.isempty()){
                  stmt.setString(1, city);
                  }





                  share|improve this answer




























                    0












                    0








                    0







                    String getResult = "SELECT id_housing, name, description_short, price, 
                    photo FROM housing WHERE init_date <= ? AND end_date >= ? AND
                    price = ? AND guests >= ?";
                    if(city != null && !city.isempty()){
                    getResult += " AND city = ? "
                    }

                    PreparedStatement stmt = con.prepareStatement(getResult);
                    if(city != null && !city.isempty()){
                    stmt.setString(1, city);
                    }





                    share|improve this answer















                    String getResult = "SELECT id_housing, name, description_short, price, 
                    photo FROM housing WHERE init_date <= ? AND end_date >= ? AND
                    price = ? AND guests >= ?";
                    if(city != null && !city.isempty()){
                    getResult += " AND city = ? "
                    }

                    PreparedStatement stmt = con.prepareStatement(getResult);
                    if(city != null && !city.isempty()){
                    stmt.setString(1, city);
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 14 '18 at 23:38

























                    answered Nov 14 '18 at 23:28









                    JustinJustin

                    1,0131511




                    1,0131511























                        0














                        One way to achieve this is to have a query stub/template into which you dynamically append the WHERE condition. You keep the bind variables in a map which maps the variable index into the corresponding value:



                        String queryStub = "SELECT id_housing, name, description_short, price, " 
                        + "photo FROM housing WHERE 1=1";

                        Map<Integer, Object> bindVariables = new HashMap<>();
                        StringBuilder sb = new StringBuilder(queryStub);
                        int paramIndex = 1;

                        if (city != null && !city.isEmpty()) {
                        sb.append(" AND city = ?")
                        bindVariables.put(paramIndex++, city);
                        }

                        // ... handle the other, possibly empty inputs

                        try (PreparedStatement stmt = con.prepareStatement(sb.toString());) {

                        for (Map.Entry<Integer, Object> e : bindVariables.entrySet()) {
                        stmt.setObject(e.getKey(), e.getValue());
                        }

                        ResultSet rs = stmt.executeQuery();
                        // ...
                        }





                        share|improve this answer






























                          0














                          One way to achieve this is to have a query stub/template into which you dynamically append the WHERE condition. You keep the bind variables in a map which maps the variable index into the corresponding value:



                          String queryStub = "SELECT id_housing, name, description_short, price, " 
                          + "photo FROM housing WHERE 1=1";

                          Map<Integer, Object> bindVariables = new HashMap<>();
                          StringBuilder sb = new StringBuilder(queryStub);
                          int paramIndex = 1;

                          if (city != null && !city.isEmpty()) {
                          sb.append(" AND city = ?")
                          bindVariables.put(paramIndex++, city);
                          }

                          // ... handle the other, possibly empty inputs

                          try (PreparedStatement stmt = con.prepareStatement(sb.toString());) {

                          for (Map.Entry<Integer, Object> e : bindVariables.entrySet()) {
                          stmt.setObject(e.getKey(), e.getValue());
                          }

                          ResultSet rs = stmt.executeQuery();
                          // ...
                          }





                          share|improve this answer




























                            0












                            0








                            0







                            One way to achieve this is to have a query stub/template into which you dynamically append the WHERE condition. You keep the bind variables in a map which maps the variable index into the corresponding value:



                            String queryStub = "SELECT id_housing, name, description_short, price, " 
                            + "photo FROM housing WHERE 1=1";

                            Map<Integer, Object> bindVariables = new HashMap<>();
                            StringBuilder sb = new StringBuilder(queryStub);
                            int paramIndex = 1;

                            if (city != null && !city.isEmpty()) {
                            sb.append(" AND city = ?")
                            bindVariables.put(paramIndex++, city);
                            }

                            // ... handle the other, possibly empty inputs

                            try (PreparedStatement stmt = con.prepareStatement(sb.toString());) {

                            for (Map.Entry<Integer, Object> e : bindVariables.entrySet()) {
                            stmt.setObject(e.getKey(), e.getValue());
                            }

                            ResultSet rs = stmt.executeQuery();
                            // ...
                            }





                            share|improve this answer















                            One way to achieve this is to have a query stub/template into which you dynamically append the WHERE condition. You keep the bind variables in a map which maps the variable index into the corresponding value:



                            String queryStub = "SELECT id_housing, name, description_short, price, " 
                            + "photo FROM housing WHERE 1=1";

                            Map<Integer, Object> bindVariables = new HashMap<>();
                            StringBuilder sb = new StringBuilder(queryStub);
                            int paramIndex = 1;

                            if (city != null && !city.isEmpty()) {
                            sb.append(" AND city = ?")
                            bindVariables.put(paramIndex++, city);
                            }

                            // ... handle the other, possibly empty inputs

                            try (PreparedStatement stmt = con.prepareStatement(sb.toString());) {

                            for (Map.Entry<Integer, Object> e : bindVariables.entrySet()) {
                            stmt.setObject(e.getKey(), e.getValue());
                            }

                            ResultSet rs = stmt.executeQuery();
                            // ...
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 14 '18 at 23:47

























                            answered Nov 14 '18 at 23:35









                            Mick MnemonicMick Mnemonic

                            6,58421924




                            6,58421924























                                -1














                                Unfortunately. you need a separate query for this case.



                                This is one reasons it's often not a good idea to use raw JDBC to access a database. With complex queries, you end up with a bunch of error-prone logic that builds pieces and concatenates them.
                                If you don't have many of these cases, then just use two different queries.



                                But if you keep running into more of these queries, then there are plenty of libraries that can help with everything from opening connections to safely executing queries without having to build different queries using raw strings. Jooq and mybatis come to mind.






                                share|improve this answer


























                                • he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

                                  – Justin
                                  Nov 14 '18 at 23:36











                                • @Justin You're right.

                                  – Malt
                                  Nov 14 '18 at 23:40
















                                -1














                                Unfortunately. you need a separate query for this case.



                                This is one reasons it's often not a good idea to use raw JDBC to access a database. With complex queries, you end up with a bunch of error-prone logic that builds pieces and concatenates them.
                                If you don't have many of these cases, then just use two different queries.



                                But if you keep running into more of these queries, then there are plenty of libraries that can help with everything from opening connections to safely executing queries without having to build different queries using raw strings. Jooq and mybatis come to mind.






                                share|improve this answer


























                                • he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

                                  – Justin
                                  Nov 14 '18 at 23:36











                                • @Justin You're right.

                                  – Malt
                                  Nov 14 '18 at 23:40














                                -1












                                -1








                                -1







                                Unfortunately. you need a separate query for this case.



                                This is one reasons it's often not a good idea to use raw JDBC to access a database. With complex queries, you end up with a bunch of error-prone logic that builds pieces and concatenates them.
                                If you don't have many of these cases, then just use two different queries.



                                But if you keep running into more of these queries, then there are plenty of libraries that can help with everything from opening connections to safely executing queries without having to build different queries using raw strings. Jooq and mybatis come to mind.






                                share|improve this answer















                                Unfortunately. you need a separate query for this case.



                                This is one reasons it's often not a good idea to use raw JDBC to access a database. With complex queries, you end up with a bunch of error-prone logic that builds pieces and concatenates them.
                                If you don't have many of these cases, then just use two different queries.



                                But if you keep running into more of these queries, then there are plenty of libraries that can help with everything from opening connections to safely executing queries without having to build different queries using raw strings. Jooq and mybatis come to mind.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 14 '18 at 23:39

























                                answered Nov 14 '18 at 23:26









                                MaltMalt

                                16.8k34163




                                16.8k34163













                                • he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

                                  – Justin
                                  Nov 14 '18 at 23:36











                                • @Justin You're right.

                                  – Malt
                                  Nov 14 '18 at 23:40



















                                • he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

                                  – Justin
                                  Nov 14 '18 at 23:36











                                • @Justin You're right.

                                  – Malt
                                  Nov 14 '18 at 23:40

















                                he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

                                – Justin
                                Nov 14 '18 at 23:36





                                he doesn't want to return only rows where city is null if city is not defined. he wants to return rows with any city, so you just have to drop the city from the where clause.

                                – Justin
                                Nov 14 '18 at 23:36













                                @Justin You're right.

                                – Malt
                                Nov 14 '18 at 23:40





                                @Justin You're right.

                                – Malt
                                Nov 14 '18 at 23:40


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310162%2fhow-to-remove-a-condition-from-where-clause-if-specific-value-is-null-using-pr%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Xamarin.iOS Cant Deploy on Iphone

                                Glorious Revolution

                                Dulmage-Mendelsohn matrix decomposition in Python