简体   繁体   中英

How can I get rid of a trailing AND in Java

This is a dumb question, but how can I delete a trailing AND in a sql statement in Java?

I'm dynamically generating the statement based on the Profile object I give it. So, if the object has "name = person1" and "address = example road", the statement should be:

select * from Profile where name = 'person1' and address = 'example road'

The issue is that I'm using a for loop to iterate through the declared fields of the object, and so it adds an extra AND to the end:

select * from Profile where name = 'person1' and address = 'example road' and

What would be the best way to get rid of a trailing AND?

Some would simply trim the final "and" from the end of the resulting string, but it's usually better to avoid writing the final and in the first place.

If your loop looks something like this:

for (String sqlCondition : sqlConditionsList) {
    sqlStatement.append(sqlCondition).append(" and ");
}

Then I'd recommend changing it to something like this:

boolean separatorNeeded = false;
for (String sqlCondition : sqlConditionsList) {
    if (separatorNeede) {
        sqlStatement.append(" and ");
    }
    sqlStatement.append(sqlCondition);
    separatorNeeded = true;
}

This will only add the "and" separator when it's actually needed, between consecutive items from the list you are iterating.

You should be using a prepared statement. Building a query like this leaves you open to SQL injection and other attacks.

If you must continue with your current approach, then a quick fix would be to strip off the final AND via regex:

String sql = "select * from Profile where name = 'person1' and address = 'example road' and";
sql = sql.replaceAll("(?i)\\s+and$", "");

Demo

You should use prepared statements or ORM. But if you still want to do that in this error-prone way, you can do it like this:

public static void main(String args[]) {
    String[] params = new String[3];

    params[0] = "x = y";
    params[1] = "z = a";
    params[2] = "b = d";

    String result = String.join(" and ", params);

    System.out.println(result);

}

Using join method is imho better solution than messing with trailing and.

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