使用JdbcTemplate进行动态查询

时间:2016-02-03 06:18:03

标签: java mysql jdbctemplate

我有一个关于使用JdbcTemplate进行动态查询的问题。

我的代码如下:

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

现在我的问题是我需要相同数量的"值"按照自动生成插入查询中的问号。

现在,值变量被视为一个字符串,所以如果我有2个或更多的问号,那么在值变量中只有一个用逗号分隔的完整字符串,因此它不起作用。

请参阅下面的查询:

INSERT INTO tablename (fname, lname) VALUES ("abc, xyz") ;

我想要如下:

INSERT INTO tablename (fname, lname) VALUES ("abc", "xyz") ;

1 个答案:

答案 0 :(得分: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);