在 Django 中执行原始 sql 时出现问题。
res = []
start = '2017-12-08T01:56:56.701Z'
end = '2020-12-08T01:56:56.701Z'
with connection.cursor() as cursor:
raw_sql = '''
select
case
when content like '%products%' then 'Products'
else 'Others'
end as name,
count(id) as times
from mytable
where somefield LIKE "%somefieldcontent%"
and created between '%s' and '%s'
'''
cursor.execute(raw_sql, [start, end])
res = cursor.fetchall()
它引发此错误:不支持的格式字符'''(0x27)
我试图直接在mysql中执行这个sql,它可以工作。但它在 Django 环境中不起作用。我认为我对字符串做的一定有问题。
基本上我想使用 params 而不是 concat 来构建 SQL 语句。有任何想法吗?谢谢!