How to remove a condition from where clause, if specific value is null (using prepared statements)
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
add a comment |
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
One option is just to construct yourgetResult
based on some conditions, so, for example, ifcity == 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
add a comment |
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
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
java mysql servlets prepared-statement
asked Nov 14 '18 at 23:13
Keka BronKeka Bron
10610
10610
One option is just to construct yourgetResult
based on some conditions, so, for example, ifcity == 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
add a comment |
One option is just to construct yourgetResult
based on some conditions, so, for example, ifcity == 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
add a comment |
4 Answers
4
active
oldest
votes
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 >= ?";
add a comment |
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);
}
add a comment |
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();
// ...
}
add a comment |
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.
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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 >= ?";
add a comment |
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 >= ?";
add a comment |
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 >= ?";
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 >= ?";
answered Nov 14 '18 at 23:25
Naeem KhanNaeem Khan
699
699
add a comment |
add a comment |
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);
}
add a comment |
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);
}
add a comment |
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);
}
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);
}
edited Nov 14 '18 at 23:38
answered Nov 14 '18 at 23:28
JustinJustin
1,0131511
1,0131511
add a comment |
add a comment |
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();
// ...
}
add a comment |
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();
// ...
}
add a comment |
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();
// ...
}
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();
// ...
}
edited Nov 14 '18 at 23:47
answered Nov 14 '18 at 23:35
Mick MnemonicMick Mnemonic
6,58421924
6,58421924
add a comment |
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
One option is just to construct your
getResult
based on some conditions, so, for example, ifcity == 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