Correct way to use StringBuilder in SQL

前端 未结 6 1946
野的像风
野的像风 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条回答
  •  时光取名叫无心
    2020-11-28 22:47

    When you already have all the "pieces" you wish to append, there is no point in using StringBuilder at all. Using StringBuilder and string concatenation in the same call as per your sample code is even worse.

    This would be better:

    return "select id1, " + " id2 " + " from " + " table";
    

    In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:

    return "select id1, id2 from table";
    

    Using new StringBuilder().append("select id1, ").append(" id2 ")....toString() will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.

    If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.

    I have an article on String / StringBuffer which I wrote a while ago - before StringBuilder came along. The principles apply to StringBuilder in the same way though.

提交回复
热议问题