通过pymysql执行查询不会返回与在MySQL中运行相同的结果

时间:2018-01-27 01:15:38

标签: mysql python-3.x pymysql

我是Python和PyMySQL的新手,所以我可能会错误配置。

我正在连接到MySQL而没有任何问题。我测试了它在表上执行 SELECT DESC ,并且能够查看结果。

我现在有一个查询,我将日期参数替换为,并希望返回列数(客户)和客户总数乘以一个值。

客户数量正确回归,但产品计算返回。在执行查询之前,我将其打印到控制台并将其复制到MySQLWorkbench以运行,并返回正确的值。

在我的 main 模块中,我连接到数据库并获取游标。然后,我获取要在查询中使用的日期值,并调用执行查询的函数。

connection = dbConnection()
cursor = connection.cursor()
startDate = input("enter start date (yyyy-mm-dd): ").strip()
endDate = input("enter end date (yyyy-mm-dd): ").strip()
my_queries.queryTotals(cursor, startDate, endDate)
connection.close()

在我的 my_queries 模块中,我有查询并将输入的日期替换为查询字符串,然后执行查询并获取结果:

totalsSQL = '''select
@total:=count(cus.customer_id) as customers, format(@total * 1.99, 2) as total
from customer cus
join membership mem on mem.membership_id=cus.current_membership_id
where mem.request='START'
and (mem.purchase_date > (unix_timestamp(date('{}'))*1000)  and mem.purchase_date < unix_timestamp(date('{}'))*1000);'''

formattedSQL = totalsSQL.format(startDate, endDate)

cursor.execute(formattedSQL)
result = cursor.fetchone()

我得到(32,无)的结果,而不是获得第二列值的数值。

我在这里缺少什么?

感谢。

1 个答案:

答案 0 :(得分:0)

您不能将变量用于聚合函数,稍后会在同一SELECT列表中引用它。在选择所有行之前,聚合不会获取其值,但在选择行时会计算其他列。

在这两个地方使用COUNT(*)

SELECT COUNT(*) AS customers, FORMAT(COUNT(*) * 1.99, 2) AS total
join membership mem on mem.membership_id=cus.current_membership_id
where mem.request='START'
and (mem.purchase_date > (unix_timestamp(date('{}'))*1000) 
and mem.purchase_date < unix_timestamp(date('{}'))*1000)

另外,为防止SQL注入,您应该使用参数化查询,而不是用format()替换变量。

totalsSQL = '''
    SELECT COUNT(*) AS customers, FORMAT(COUNT(*) * 1.99, 2) AS total
    join membership mem on mem.membership_id=cus.current_membership_id
    where mem.request='START'
    and (mem.purchase_date > (unix_timestamp(date(%s))*1000) 
    and mem.purchase_date < unix_timestamp(date(%s))*1000)
'''
cursor.execute(totalsSQL, (startDate, endDate))
相关问题