Raghvendra Singh Raghvendra Singh - 3 months ago 11
SQL Question

replacing parameters values with ? in an sql query

Lets say I have a query like this:

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


I want to replace all the parameters passed in this query with a question mark, to get something like this:

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


Note that this is just an example and a query can be much more complex. I just want to replace all the parameters passed with a question mark.

Any idea how to achieve this?

Answer

It's simple using replaceAll function,

String str = "INSERT INTO users (lastname, age, city,email, firstname) VALUES ('Doe',30,'Austin', 'jon@ds.com', 'Jon')";
System.out.println(str.replaceAll("'.+?'|\\d+","?"));  


Output:


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