我在下面提供了三個示例SQL查詢。這些工作都很好,在MySQL [db] >
環境中直接從終端執行時返回預期的表格輸出。當通過PyMySQL執行時,在MySQL終端中運行的查詢失敗
對方這些查詢保存在一個叫做queries.py
的python文檔中。後面的兩個查詢在通過pymysql
傳遞給db時正常工作,但第一個查詢返回一個空數組。
我已經簽出this post,this post和this post,他們都沒有解決這個問題。
下面是我使用的Python測試示例代碼(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
傳遞給DB空白數組:
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`;"""
有趣......好像你正確使用引號,我卑微的建議是頂級簡化您的where子句,並逐步增加的條件。 –
Python正在咀嚼字符串文字中的一些反斜槓字符。您需要在Python中將字符串文字中的反斜槓加倍。總共*四個*反斜槓,在SQL文本中獲得*兩個*反斜槓傳遞給MySQL,以便MySQL將它視爲* one *反斜槓字符。 – spencer7593