Django Raw查询

时间:2014-11-04 05:20:55

标签: python mysql django

lists = []
lists = cursor.execute(
    "select a.employee_id,a.first_name,"
    "c.breakfast_count, b.lunch_count,"
    "d.dinner_count from qpscsmas_employee_details a,"
    "qpscsmas_emp_lunch b,"
    "qpscsmas_emp_breakfast c,"
    "qpscsmas_emp_dinner d "
    "where a.rfidcardno = %s "
    "and b.rfidcardno = %s "
    "and c.rfidcardno = %s "
    "and d.rfidcardno = %s,"
    "['s','s','s','s']"
)
print lists

以上查询给我一个空列表。

问题在于它也没有显示任何错误。

当我给出确切的值代替参数

时,它在MySQL中工作正常

1 个答案:

答案 0 :(得分:1)

首先,您需要从参数列表中删除双引号,并用查询字符串中的逗号分隔,例如:

cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])

执行查询后,您需要获取行,请参阅Executing custom SQL directly。您可以获取下一个(cursor.fetchone())或获取所有行(cursor.fetchall())。

示例:

row = cursor.fetchone()
rows = cursor.fetchall()

此清理后的查询应该有效:

cursor.execute(
    "select a.employee_id,a.first_name,"
    "c.breakfast_count, b.lunch_count,"
    "d.dinner_count from qpscsmas_employee_details a,"
    "qpscsmas_emp_lunch b,"
    "qpscsmas_emp_breakfast c,"
    "qpscsmas_emp_dinner d "
    "where a.rfidcardno = %s "
    "and b.rfidcardno = %s "
    "and c.rfidcardno = %s "
    "and d.rfidcardno = %s", 
    ['s','s','s','s']
)