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
ANDat the end every time you append another aspect of your query, instead start withAND(for the first entry,WHERE). Now the problem has gone away entirely. If thatWHEREthing is annoying, you're always free to start a query withSELECT stuff FROM table WHERE trueand then you can get in the habit of writing each additional query rule asAND thingie = valuefrom 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.