下面我提供了三个示例sql查询。每一个都可以很好地工作,当直接从中的终端执行时,返回预期的表输出 MySQL [db] >
环境。
这些查询彼此保存在一个名为 queries.py
. 后两个查询在通过 pymysql
,但第一个返回空数组。
我查看了这篇文章,这篇文章,还有这篇文章,但是没有一篇文章提到这个问题。
下面是我用来在python(version)中测试的示例代码 3.5
):
import pymysql
import params
import queries
conn = pymysql.connect(
host = params.HOST,
user = params.USER,
password = params.PWD,
db = 'db',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor,
autocommit = True)
test_queries = [queries.VETTED, queries.CREATED, queries.CLOSED_OPPS]
with conn.cursor() as cursor:
for query in test_queries:
cursor.execute(query)
print(cursor.fetchall())
() #..blank output -- doesn't make sense because corresponding query works in MySQL env
[...] #..expected output from query 2
[...] #..expected output from query 3
这是什么 queries.py
看起来像。在mysql中执行时,每个查询都会返回预期的输出,但是第一个查询, VETTED
,通过 pymysql
:
VETTED = """
SELECT
date_format(oa.logged_at, '%Y-%m-%d') as `action_date`,
count(1) `count`
FROM
crm_audit_field oaf,
crm_audit oa,
crm_sales_lead lead
WHERE
oa.id = oaf.audit_id AND
oaf.field = 'status' AND
(
oaf.new_text = 'Qualified' OR
oaf.new_text = 'Disqualified' OR
oaf.new_text = 'Canceled'
) AND
oa.object_class = 'CRM\\Bundle\\SalesBundle\\Entity\\Lead' AND
lead.id = oa.object_id AND
(lead.status_id = 'qualified' OR lead.status_id = 'canceled')
GROUP BY
`action_date`;"""
CREATED = """
SELECT
DATE_FORMAT(lead.createdat, '%Y-%m-%d') as `creation_date`,
count(1)
FROM
crm_sales_lead `lead`
GROUP BY
creation_date;"""
CLOSED_OPPS = """
SELECT
date_format(closed_at, '%Y-%m-%d') `close_date`,
count(1) `count`
FROM
crm_sales_opportunity
WHERE
status_id = 'won'
GROUP BY
`close_date`;"""
1条答案
按热度按时间iklwldmw1#
我认为在python字符串文本中需要四个反斜杠来表示mysql需要的两个反斜杠字符,来表示一个反斜杠字符。
mysql需要字符串文本中的两个反斜杠来表示反斜杠字符。您的sql文本在mysql中工作,因为字符串文本包含两个反斜杠字符。
但是在python代码中,发送到mysql的sql语句只包含一个反斜杠字符。
这是因为python还需要字符串文本中的两个反斜杠来表示反斜杠字符,就像mysql一样。
所以,在python中。。。
表示仅包含一个反斜杠字符的字符串:
'CRM\Bundle'
要获取包含两个反斜杠字符的字符串:'CRM\\Bundle'
在python文本中需要四个反斜杠,如下所示: