用?替换参数值?在一个SQL查询中

时间:2016-08-10 16:32:12

标签: java sql regex

假设我有这样的查询:

INSERT INTO users (lastname, age, city, email, firstname) VALUES ('Doe',30,'Austin', 'jon@ds.com', 'Jon')

我想用问号替换此查询中传递的所有参数,以获得如下内容:

INSERT INTO users (lastname, age, city, email, firstname) VALUES (?,?,?,?,?)

请注意,这只是一个示例,查询可能要复杂得多。我只想用问号替换所有传递的参数。

知道怎么做到这一点?

1 个答案:

答案 0 :(得分:-1)

使用replaceAll函数很简单,

String str = "INSERT INTO users (lastname687878, age1, city55,email, firstname66) VALUES (33,30,'Austin', 'jon@ds.com', 'Jon')";
System.out.println(str.replaceAll("'.+?'","?").replaceAll(",\\d+", ",?").replaceAll("\\(\\d+", "(?"));  

输出:

INSERT INTO users (lastname687878, age1, city55,email, firstname66) VALUES (?,?,?, ?, ?)