0

I am writing an app that allows the user to create custom SQL queries with user input.

I add the falue from each JTextFields to the array using

for(JTextField field : fields){
 if (!field.getText().equals("")){
   rows.add(field.getText());
 }
}

When i output an array it is wrapped in square brackets

[arVal1, arVal2, etc, etc]

So when i inser the array into the query string it looks like this:

INSERT INTO table ([arval1, arval2, arVal3]) VALUES ([bla, bla, bla])

When i run the query for some reason i get: ORA-00928: missing SELECT keyword error; but if i have a default string for the query like:

INSERT INTO table (arval1, arval2, arVal3) VALUES (bla, bla, bla)

it works fine.

Im looking to get rid of the [] when outputting the array

Thank You

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
slex
  • 855
  • 2
  • 10
  • 20

3 Answers3

2

You shouldn't rely on the toString method of the array.

Using Guava, try Joiner.on(",").join(myArray);

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
1

If you cannot use Guava (but I recommend it :) )

StringBuilder builder = new StringBuilder();
builder.add("INSERT INTO table (");
for(int i=0; i<rows.length: rows){
   builder.add(row);
   if(i<rows.length -1){
      builder.add(",")
   }
}
builder.add(") VALUES (");
....

To complete, with Guava, it looks like this:

Joiner commaJoiner = Joiner.on(", ");
"INSERT INTO table (" + commaJoiner.join(rows) + " VALUES " + commaJoiner.join(values)
sly7_7
  • 11,961
  • 3
  • 40
  • 54
  • how do i import the lib? import com.google.common.base.Joiner; doesnt work. – slex Nov 29 '10 at 17:48
  • 1
    You also need to add the guava jar to your classpath. How you do this depends on the context in which the code is running. If you're running from an IDE, there should be an import library or library management screen somewhere. – Stefan Kendall Nov 29 '10 at 18:24
0

Maybe an overly complicated solution, but try overriding toString()

 ArrayList<String> rows = new ArrayList<String>()
    {
        public String toString()
        {
            StringBuffer retVal = new StringBuffer();
            for(int i = 0; i < size(); i++)
            {
                retVal.append(this.get(i));
                if(i < size() - 1)
                {
                    retVal.append(",");
                }
            }
            return retVal.toString();
        }
    };
user489041
  • 27,916
  • 55
  • 135
  • 204
  • - if no conccurency, use StringBuilder instead of StringBuffer, and, I think it's better to iterate over the list rather than overriding the toString method – sly7_7 Nov 29 '10 at 17:32