Looptech
Looptech

Reputation: 223

Getting rid of comma

Im newbie in java and need help with getting rid of a comma in an sql query. anyone who can guide me in the right direction?

    query = "UPDATE " + tablename + " SET ";
    for(int i=0; i< columnnames.size(); i++)
    {
    query+= "'" + columnnames.get(i)  + "' = '" + row[i] + "',";
     }
     query = StripLastComma(query); //Not sure how to do this in Java.
    query +="' WHERE " + FirstColumn + " = '" + rowstandard + "'";

Upvotes: 0

Views: 124

Answers (3)

Bohemian
Bohemian

Reputation: 425053

Firstly, you have a bug: you are quoting your column names when you should not.

The comma issue is easiest handled by making the logic different for the first iteration and putting the comma before the content, which neatly handles the edge case of there being only one column:

if (i > 0)
    query += ",";
query += columnnames.get(i) + " = '" + row[i] + "'";

Your code is vulnerable to SQL injection, but if the only client is your own code (ie you know the new values of the columns are "safe") it's OK.

Upvotes: 0

Jonathan Drapeau
Jonathan Drapeau

Reputation: 2610

Disregarding the already mentionned SQL injection problem, I would use a StringBuilder and do it like this to avoid that last comma.

StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("UPDATE " + tablename + " SET ");
for(int i = 0; i < columnnames.size(); i++) {
  if (i != 0) {
    queryBuilder.append(",");
   }

  queryBuilder.append("'" + columnnames.get(i)  + "' = '" + row[i] + "'");
}

queryBuilder.append("' WHERE " + FirstColumn + " = '" + rowstandard + "'");
query = queryBuilder.toString();

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

You can do this:

query = query.substring(0, query.length()-1);

at the place of "//Not sure how to do this in Java.".

But also:

1) As Makoto wrote use PreparedStatement. Also read a bit
about SQL injection and how to protect yourself from it.

2) Using StringBuilder instead of String would be better for your case.
That's because, it seems you use String and it is immutable.
So when deleting the last comma, you're actually creating a
whole new String object which is really not needed as other pointed
out in their comments.

Upvotes: 2

Related Questions