Reputation: 433
I have one question regarding make dynamic query with JdbcTemplate.
My code is as below :
String insertQueries = "INSERT INTO " + tablename;
StringJoiner joiner = new StringJoiner(",");
StringJoiner joiner1 = new StringJoiner(",");
StringJoiner joiner2 = new StringJoiner(",");
while (mapIterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
key = joiner.add((String) mapEntry.getKey()).toString();
// value = joiner1.add("\"" + (String) mapEntry.getValue() + "\"").toString();
value = joiner1.add("\"" + (String) mapEntry.getValue() + "\"").toString();
value1 = joiner2.add("?").toString();
}
insertQueries += " (" + key + ")";
insertQueries += " VALUES ("+value1+")" ;
int row = jdbcTemplate.update(insertQueries, value);
Now my question is that I want same number of "value" as per auto generate question marks in insert query.
Right now, the value variable consider as one string so if I have 2 or more question marks then in value variable only one full string with comma separated so it's not working.
See below my query :
INSERT INTO tablename (fname, lname) VALUES ("abc, xyz") ;
And I want as below :
INSERT INTO tablename (fname, lname) VALUES ("abc", "xyz") ;
Upvotes: 0
Views: 6120
Reputation: 826
**StringJoiner joiner2 = new StringJoiner(",", "(", ")");**
while (mapIterator.hasNext()) {
//change in value1 as
value = "\"" + (String) mapEntry.getValue() + "\"";
value1 = joiner2.add(value);
myvalue = joiner2.add("?");
}
//change insertQueries as with value as (? ,?)
insertQueries += " VALUES "+ myvalue+"" ;
//get value1 as ("abc", "xyz")
//update query as
int row = jdbcTemplate.update(insertQueries, value1);
Upvotes: 1