I’m refactoring my application. One thing that I’m actually doing is:
String sql = "select column1 from table2";
boolean isOrderbyAdded = false;
for(int i=1; i<N; i++) { // N is a known integer (e.g. 5)
if(column[i]!=null) {
if(!isOrderbyAdded) {
sql += " order by "
isOrderbyAdded = true;
} else {
sql += ", "
}
sql += column[i];
}
}
I want to change this into a prepared statement. Is there a way to write one statement that checks whether each column name was specified before eventually sorting the results?
My query is executed millions of time a day. I thought that a prepared statement would save me some compilation time.
This can’t be done using basic SQL libraries. You’re stuck, but you have a few options.
String.formatmay be faster for you.StringBuilderwith.appendwill definitely be faster for you.Strings, unless it’s not done very often (then it doesn’t matter).StringBuilderis always faster, especially if you can predict thecapacitywell. But the default of 16 more characters is likely to be sufficient here (though, if it’s not, use a larger one).Here’s the version of your code that uses
StringBuilder, though the Spring way is probably best, but would require a lot more work on your part. Check out Spring here.