StringBuffer or StringBuilder for my query

Some Java Guy picture Some Java Guy · Oct 19, 2015 · Viewed 7.1k times · Source

I understand first one is synchronized and the later one is unsynchronized with faster response time.

I am using StringBuffer for appending a SQL query. Transferring to StringBuilder would make it faster(My question is especially in regards to SQL)?

Is it advisable to use StringBuilder around SQl query appending?

My Current Code

public boolean saveData (Connection conn,MyObject) throws SQLException {
..
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
StringBuffer sSubQry = new StringBuffer();                      
sSubQry.append (" select ID, STATEID, TYPEID, LANGID, SEQ, ");
sSubQry.append (" SECTIONSEQ, CODE, NAME, INPUTNAME, ");
sSubQry.append (" .., .., ..,");
sSubQry.append (" .., .., ..,");
..
..
pstmt = conn.prepareStatement(sSubQry.toString());
rs = pstmt.executeQuery();
while (rs.next ())
 {
 ..
 }
}

By transferring it to StringBuilder have any +ve or -ve effects

public boolean saveData (Connection conn,MyObject) throws SQLException {
..
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
StringBuilder sSubQry = new StringBuilder();                        
sSubQry.append (" select ID, STATEID, TYPEID, LANGID, SEQ, ");
sSubQry.append (" SECTIONSEQ, CODE, NAME, INPUTNAME, ");
sSubQry.append (" .., .., ..,");
sSubQry.append (" .., .., ..,");
..
pstmt = conn.prepareStatement(sSubQry.toString());
rs = pstmt.executeQuery();
while (rs.next ())
 {
 ..
 }
}

Answer

chiastic-security picture chiastic-security · Oct 19, 2015

This is all being done in a single thread, so yes, a StringBuilder is fine (but see comments about whether it's appropriate to construct SQL this way at all).

Whenever you have a sequence of steps like this, where you create a local variable, and then never pass a reference to it to any other method, and you never return it, you can be sure only the current thread can access it.

(Usually, if you're passing something to another thread, you'll be aware that that's what you're doing.)