0

This is my code.

Code 1 : StringBuilder sb = new StringBuilder("select * from user");

Code 2 : StringBuffer sb1 = new StringBuffer("select * from user");

Which one is correct? and Why?

EDIT : I have seen in some code StringBuffer is used and in other StringBuilder is used. For the query like this, which will be passed to get PreparedStatement, which approach is better. Also tell me what would happen for insert queries.

Subash L
  • 215
  • 1
  • 3
  • 11
  • 2
    Why do you think only one can be correct? (Both of them suggest that you're going to be building SQL dynamically, which is almost certainly a far bigger problem than this choice...) – Jon Skeet Jul 21 '15 at 06:24
  • @JonSkeet Jon I have edited. – Subash L Jul 21 '15 at 06:29
  • @JonSkeet Building dynamic SQL is big problem?. Jon I need to know whether the synchronization affects in the above code. What difference will that make in the query. – Subash L Jul 21 '15 at 06:38
  • 1
    Building dynamic SQL tends to be done badly, including values directly instead of using parameterized SQL. (Not always, but often.) As for the synchronization and the query - by the time you need to issue the query, you'll have converted this to a String anyway, so it will have no impact on that at all. It may take *ever so slightly* longer to construct with StringBuffer, but that's got nothing to do with using it for SQL. (And is bound to be irrelevant compared with the cost of executing the query.) – Jon Skeet Jul 21 '15 at 07:12

0 Answers0