% 混淆 python 原始 sql 查询 [英] % confuses python raw sql query

查看:40
本文介绍了% 混淆 python 原始 sql 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照这个问题,我试图截断"所有表在 python 中使用以下原始 sql 命令与某个 django 应用程序相关:

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")

唉,我收到以下错误:

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

LIKE 中的% 有问题吗?我该如何解决?

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

推荐答案

您是否尝试过 %%?在 Python 字符串格式中引用了一个 %.

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

这篇关于% 混淆 python 原始 sql 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆