Format an SQL query in Python without executing it
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.
精彩评论