tags:

views:

218

answers:

10

Hi,

I want to execute a query like select ID from "xyz_DB"."test" where user in ('a','b')

so the corresponding code is like

String s="(";
for(String user:selUsers){
    s+= " ' " + user + " ', ";
}
s+=")";

Select ID from test where userId in s;

The following code is forming the value of s as ('a','b',) i want to remove the comma after the end of array how to do this ?

A: 

i would do s+= " ,'" + user + "'"; (place the comma before the value) and add a counter to the loop where i just do s = "'" + user + "'"; if the counter is 1 (or 0, depending on where you start to count).

oezi
can u explain it clearly
sarah
@sarah, I think my answer clarifies his suggestion.
aioobe
as aioobe says, see his answer for some code. i wanted you to think yourself, not giving you the premade code, so you realy understand what you are doing.
oezi
A: 

(N.B. - I'm not a Java guy, so the syntax may be wrong here - apologies if it is).

If selUsers is an array, why not do:

selUsers.join(',');

This should do what you want.

EDIT:

Looks like I was wrong - I figured Java had this functionality built-in. Looks like the Apache project has something that does what I meant, though. Check out this SO answer: http://stackoverflow.com/questions/1515437/java-function-for-arrays-like-phps-join/1515450#1515450

inkedmn
No `join` method exists on arrays or collections in Java.
Stephen C
@inkedmn: Yeah, -sort of- unfortunately Java is purely OO language with no to little functional capabilities which `join` is one of.
Esko
+3  A: 

Here is one way to do this:

String s = "(";
boolean first = true;
for(String user : selUsers){
    if (first) {
        first = false;
    } else {
        s += ", ";
    }
    s += " ' " + user + " '";
}
s += ")";

But it is more efficient to use a StringBuilder to assemble a String if there is looping involved.

StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
    if (first) {
        first = false;
    } else {
        sb.append(", ");
    }
    sb.append(" ' ").append(user).append(" '");
}
sb.append(")");
String s = sb.toString();
Stephen C
+2  A: 

This does the trick.

String s = "";
for(String user : selUsers)
    s += ", '" + user + "'";

if (selUsers.size() > 0)
    s = s.substring(2);

s = "(" + s + ")";

But, a few pointers:

  • When concatenating strings like this, you are advised to work with StringBuilder and append.
  • If this is part of an SQL-query, you probably want to sanitize the user-names. See xkcd: Exploits of a Mom for an explanation.

For fun, a variation of Stephen C's answer:

StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
    if (!first || (first = false))
        sb.append(", ");
    sb.append('\'').append(user).append('\'');
}
sb.append(')');

you could even do the loop it like this :-)

for(String user : selUsers)
    sb.append(!first || (first=false) ? ", \'" : "\'").append(user).append('\'');
aioobe
A: 

Use the 'old style' of loop where you have the index, then you add the comma on every username except the last:

    String[] selUsers = {"a", "b", "c"};
    String s="("; 
    for(int i = 0; i < selUsers.length; i++){
        s+= " ' " + selUsers[i] + " ' ";  
        if(i < selUsers.length -1){
            s +=" , ";
        }
    }
    s+=")";

But as others already mentioned, use StringBuffer when concatenating strings:

    String[] selUsers = {"a", "b", "c"};
    StringBuffer s = new StringBuffer("("); 
    for(int i = 0; i < selUsers.length; i++){
        s.append(" ' " + selUsers[i] + " ' ");  
        if(i < selUsers.length -1){
            s.append(" , ");
        }
    }
    s.append(")");
Kennet
A: 

Java 1.4+

s = s.replaceFirst("\\, \\)$", ")");

Edited: I forgot last space before parethesis

SourceRebels
+1  A: 

Use StringUtils.join from apache commons.

abyx
Why reinvent the wheel?
ptomli
A: 

I fully support Stephen C's answer - that's the one I wanted to suggest aswell: simply avoid adding the additional comma.

But in your special case, the following should work too:

s = s.replace(", \\)", ")");

It simply replaces the substring ", )" with a single bracket ")".

Andreas_D
A: 

StringBuilder has a perfectly good append(int) overload.

String [] array = {"1","2","3" ...}; 
StringBuilder builder = new StringBuilder(); 
 builder.append(s + "( ")
for(String i : array) 
{ 
    if(builder.length() != 0) 
        builder.append(","); 
    builder.append(i); 
} 
builder.append(" )")

Answer shamelessly copied from here

Narayan
A: 

Prior to adding the trailing ')' I'd strip off the last character of the string if it's a comma, or perhaps just replace the trailing comma with a right parenthesis - in pseudo-code, something like

if s.last == ',' then
  s = s.left(s.length() - 1);
end if;

s = s + ')';

or

if s.last == ',' then
  s.last = ')';
else
  s = s + ')';
end if;

Share and enjoy.

Bob Jarvis