Home > OS >  Convert each parameter to question mark for query statement
Convert each parameter to question mark for query statement

Time:10-04

I mean from this:

SELECT * FROM my_tab WHERE col1 = 'name1' AND col2 in(1,2,3);

how to get this:

SELECT * FROM my_tab WHERE col1 = ? AND col2 in(?,?,?);

pg_stat_statements does similar but it not saves original(with parameters) statement. I need original query also.

May be there is some open source or regex expression, which does this?

CodePudding user response:

If you have access to Python, you may try:

sql = "SELECT * FROM my_tab WHERE col1 = 'name1' AND col2 IN (1,2,3);"
output = re.sub(r'\bIN\s*\((.*?)\)', lambda m: 'IN ('   re.sub(r'\w ', '?', m.group(1))   ')', sql)
print(output)

This prints:

SELECT * FROM my_tab WHERE col1 = 'name1' AND col2 IN (?,?,?);

CodePudding user response:

You might be able to do this for specific queries, but a general solution for this question would require parsing the SQL statement, which is complicated, to say the least.

Try to find a different solution for the problem underlying your question.

  • Related