Search code examples
javaformattingarraylistora-00928

Java - output array without its formatting


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


Solution

  • 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)