0

I am working on my project and now I am having doubts about SQL query; is it okay to put the whole query in the String or it is better practice to use StringBuilder even though the query is static (it doesn't contain any variable)

private void createTheExpectedData() throws SQLException {
        String query = "SELECT products.productname, orderdetails.quantityordered, orderdetails.priceEach "
                + "FROM orderdetails "
                + "INNER JOIN products "
                + "ON orderdetails.productcode = products.productcode";
        resultSet = db.testClassQuery(query);
2
  • Try and profile both. Do you see a difference? If yes, that's your answer. If not, that's an answer as well. Commented Apr 27, 2020 at 14:56
  • 1
    I think java compiler is smart enough to optimize usage of string constants without any action from your side. Commented Apr 27, 2020 at 15:01

1 Answer 1

1

They would be equivalent here, because Java performs String concatenation with StringBuilder (since Java 5 anyway). However, since the query is static I would suggest moving it to a static constant. Then you really don't have to worry if that concatenation takes too much time. Or about creating that temp String instance on every invocation.

private static final String CREATE_QUERY = "SELECT products.productname, "
            + "orderdetails.quantityordered, orderdetails.priceEach "
            + "FROM orderdetails "
            + "INNER JOIN products "
            + "ON orderdetails.productcode = products.productcode";

private void createTheExpectedData() throws SQLException {
    resultSet = db.testClassQuery(CREATE_QUERY);
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.