I am trying to build a SQL statement using a set of values from an array list. I'll start from the beginning.
Define my arrayList
ArrayList<String[]> myRecords = new ArrayList<String[]>();
Define my array string:
String[] record = new String[2];
Then i loop though a file and split on on the comma and add the record to myRecords
while(scan.hasNext())
{
record = scan.nextLine().split(",");
myRecords.add(record);
}
So now I need to create an SQL import statement and use thoes values in the arraylist. For example.
String sql = "insert into table (parm1, parm2) Values ";
Now I want to loop though the array and put fill in param1 & param2.
for(String[] list : myRecords)
{
sqlString +=("(");
for(String list1 : list)
{
sqlString +=("'"+ list1+ "',");
}
sqlString+=("),");
}
sqlString += ';';
logger.info(sqlString);
The problem now is when I print out the SQL string it looks like this.
insert into table (parm1, parm2) Values ('value1','value2',),('value3','value4',),;
So on and so forth.
So the problem is that there is an extra comma in there at the end of value2 and value4. And after the last bracket before the ; I've gone switching it around etc, but I can't seem to figure out how i can get a proper formatted sql string.
This is how it should look.
insert into table (parm1, parm2) Values ('value1','value2'),('value3','value4');
Perhaps it's the way I am forming my for loop. Any suggestions would be great!
Add a counter and initialize it to 0, increment the counter after added a value. Only append the comma when the counter is larger than 0
int recCount = 0;
for(String[] list : myRecords)
{
if (recCount > 0)
{
sqlString += ",";
}
sqlString +=("(");
int count = 0
for(String list1 : list)
{
if (count > 0)
{
sqlString += ",";
}
sqlString += "'"+ list1+ "'";
count++;
}
sqlString+=(")");
recCount++;
}
Building SQL strings in general is not a great idea and is a major security risk
Simply:
boolean first = true;
for(String[] list : myRecords) {
if(first) {
first = false;
} else {
sqlString += ',';
}
sqlString +=("(");
for(String list1 : list) {
sqlString +=("'"+ list1+ "',");
}
sqlString+=(")"); // no more "'"
}
sqlString += ';';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.