简体   繁体   中英

Python3 Sqlite3 - How to Escape executescript Properly?

I have a query like this:

PRAGMA encoding="UTF-8";
INSERT OR IGNORE INTO {0} ({1}) VALUES ({2});
UPDATE {0} SET {1} = "{2}" WHERE {1} = "{3}";

I use this query to insert & update. But, as you can see, this is a multiline query, so I have to use executescript function, which results that I can't use placeholders like this to avoid injections:

PRAGMA encoding="UTF-8";
INSERT OR IGNORE INTO {0} ({1}) VALUES (?);
UPDATE {0} SET {1} = "?" WHERE {1} = "?";

So, is there a workaround? Do I have to change my approach or escape it without using placeholders? If so, how I can escape it to avoid possible injections? Thanks.

You can use string formatting.

command = """
PRAGMA encoding="UTF-8";
INSERT OR IGNORE INTO {0} ({1}) VALUES (?);
UPDATE {0} SET {1} = {} WHERE {1} = {};
""".format(var1, var2)

Get rid of that pragma. It only has meaning when used before any tables are created in a brand new database. Documentation .

Then in your INSERT and UPDATE statements, just use placeholders like normal. (Unfortunately, there's no way to use placeholders to indicate a table or column name, just values, so if those aren't known when you're writing out the query, you have to stick with that string formatting approach for them.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM