开发者

Format an SQL query in Python without executing it

开发者 https://www.devze.com 2023-04-08 16:35 出处:网络
Python has all sort of libraries to interface with databases, which provide a nice way to build SQL queries without worrying about SQL injections. For instance, with sqlite3:

Python has all sort of libraries to interface with databases, which provide a nice way to build SQL queries without worrying about SQL injections. For instance, with sqlite3:

for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         开发者_运维问答]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

The trouble is, I don't want to execute the query, I just want to format it and get the query as a string. I guess I could escape things myself, but it's not a very elegant solution. There has to be a way to get the formatted queries without actually connecting to a database and running them.

(The context is that I'm writing a filter which prepares a series of SQL statements from the input, but I don't want to run them on a specific database, just save them for later.)


There has to be a way to get the formatted queries without actually connecting to a database and running them

Not really.

The RDBMS handles this internally with "prepared queries" and "bind variables". The "formatted" doesn't actually exist. Anywhere.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号