Make Dynamic Query with JdbcTemplate

冷暖自知 提交于 2019-12-02 20:06:33

问题


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") ;

回答1:


**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);


来源:https://stackoverflow.com/questions/35169818/make-dynamic-query-with-jdbctemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!