Correct way to use StringBuilder in SQL

前端 未结 6 1972
野的像风
野的像风 2020-11-28 22:29

I just found some sql query build like this in my project:

return (new StringBuilder(\"select id1, \" + \" id2 \" + \" from \" + \" table\")).toString();
         


        
6条回答
  •  猫巷女王i
    2020-11-28 22:56

    In the code you have posted there would be no advantages, as you are misusing the StringBuilder. You build the same String in both cases. Using StringBuilder you can avoid the + operation on Strings using the append method. You should use it this way:

    return new StringBuilder("select id1, ").append(" id2 ").append(" from ").append(" table").toString();
    

    In Java, the String type is an inmutable sequence of characters, so when you add two Strings the VM creates a new String value with both operands concatenated.

    StringBuilder provides a mutable sequence of characters, which you can use to concat different values or variables without creating new String objects, and so it can sometimes be more efficient than working with strings

    This provides some useful features, as changing the content of a char sequence passed as parameter inside another method, which you can't do with Strings.

    private void addWhereClause(StringBuilder sql, String column, String value) {
       //WARNING: only as an example, never append directly a value to a SQL String, or you'll be exposed to SQL Injection
       sql.append(" where ").append(column).append(" = ").append(value);
    }
    

    More info at http://docs.oracle.com/javase/tutorial/java/data/buffers.html

提交回复
热议问题