简体   繁体   中英

How can I delete last word of sentence in StringBuilder?

I want to detele the last word of string in StringBuilder here is it my code:

builder.append(" where");
        if(type.equals(EnumTypePrestation.OPTIQUE)){
            builder.append(" d.idDossier=p.id and d.statut=4 and  ");

        }

builder.substring(0,builder.lastIndexOf(" ")-1);

the builder contains: WHERE d.idDossier = p.id AND d.statut = 4 AND

I want to remove the last word "AND" can anyone help me to do that!

Step 1 is generally to check the javadoc first, before asking on Stack Overflow. Had you done that, you would have found the StringBuilder.setLength() method which you can use to 'set the length'. Trivially, set the length to 4 less (that same javadoc tells you that .length() gets you the current length, so, builder.setLength(builder.length() - 4) and you have your result.

But..

It's 6, not 4.

As per your own snippet, you're adding " AND " - note the spaces. That's 6, not 4.

Swap AND

A much better way to do this is to swap where/and to the front of your appends. Instead of adding AND at the end every time you append another aspect of your query, instead start with AND (for the first entry, WHERE ). Now the problem has gone away entirely. If that WHERE thing is annoying, you're always free to start a query with SELECT stuff FROM table WHERE true and then you can get in the habit of writing each additional query rule as AND thingie = value from there.

Actually, use JDBI/JOOQ

JDBC is extremely low level and isn't really meant to be used like this. As you found, it's quite annoying to write code for it. That's because JDBC is low-level glue; it exists as common ground for DB engine builders and the JVM. Instead, use a library that makes 'talking SQL with databases from java' a lot easier, faster, and more sustainable (easier to maintain, test, and modify in face of change requests). Such as JDBI or JOOQ .

It would be more logical to do less superfluous SQL.

    int startWhere = builder.length();
    if (type == EnumTypePrestation.OPTIQUE) {
        builder.append(" and d.idDossier=p.id and d.statut=4");
    }
    if (...) {
        builder.append(" and ...");
    }
    ...
    if (builder.length() > startWhere) {
         builder.replace(startWhere, " and".length(), " where");
    }

This code still is ugly. The attempt to be efficient using a StringBuilder is even error prone.

List<String> criteria = new ArrayList<>();
if (type == EnumTypePrestation.OPTIQUE) {
    criteria.add("d.idDossier=p.id and d.statut=4");
}
...
if (!criteria.empty()) {
    builder.append(criteria.stream()
        .collect(Collectors.joining(" and ", " where ", " ");
    // Or:
    builder.append(criteria.stream()
        .collect(Collectors.joining(") and (", " where (", ")");
}

joining has here 3 parameters: separator, prefix and suffix.

There is one hard advise: do not try to make such code easier with this kind of tiny frameworks. This kind of database coding is very often done. However the next programmer has to learn it, instead of an existing library. And the chance people program around it or the API will show up deficits, is large. Better invest the time looking for an existing solution. You will save time on maintenance work (new features, difficult things with prepared statements, and so on).

The answer of rzwitserloot is to the point.

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