% confuses python raw sql query

ε祈祈猫儿з 提交于 2019-12-01 19:18:27

问题


Following this SO question, I'm trying to "truncate" all tables related to a certain django application using the following raw sql commands in python:

cursor.execute("set foreign_key_checks = 0")
cursor.execute("select concat('truncate table ',table_schema,'.',table_name,';') as sql_stmt from information_schema.tables where table_schema = 'my_db' and table_type = 'base table' AND table_name LIKE 'some_prefix%'")
for sql in [sql[0] for sql in cursor.fetchall()]:
    cursor.execute(sql)
cursor.execute("set foreign_key_checks = 1")

Alas I receive the following error:

C:\dev\my_project>my_script.py
Traceback (most recent call last):
  File "C:\dev\my_project\my_script.py", line 295, in <module>
    cursor.execute(r"select concat('truncate table ',table_schema,'.',table_name,';') as sql_stmt from information_schema.tables where table_schema = 'my_db' and table_type = 'base table' AND table_name LIKE 'some_prefix%'")
  File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 18, in execute
    sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  File "C:\Python26\lib\site-packages\django\db\backends\__init__.py", line 216, in last_executed_query
    return smart_unicode(sql) % u_params
TypeError: not enough arguments for format string

Is the % in the LIKE making trouble? How can I workaround it?


回答1:


Have you tried %%? That quotes a % in Python string-formatting.



来源:https://stackoverflow.com/questions/4833966/confuses-python-raw-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!