我使用PyMYSQL查询MySQL数据库中的数据。我想要使用的示例查询是:
SELECT count(*) AS count
FROM example
WHERE item = %s
LIMTI 1
将使用
运行query = "SELECT COUNT(*) as count FROM example WHERE item = %s LIMIT 1"
cur.execute(query,(None))
或
cur.execute(query,(10))
问题是该项的值可以为NULL,从而导致
WHERE item = NULL
哪些在MySQL中不起作用。相反应该阅读
WHERE item IS NULL
但是值也可以是整数。如何使PyMySQL调整查询以处理这两种情况?
答案 0 :(得分:0)
你可以创建一个简单的函数来捕获None
情况:
def null_for_sql(a):
return "is NULL" if not a else "= " + str(a)
然后调用这样的查询:
query = "SELECT COUNT(*) as count FROM example WHERE item %s LIMIT 1"
cur.execute(query,null_for_sql(None))
请注意,查询
中的“item”后面没有“=”评论后编辑:
def sql_none_safe_generator(query,parameter):
if parameter:
return query.replace(%param, "= " + str(parameter))
else:
return query.replace(%param, is NULL)
query = "SELECT COUNT(*) as count FROM example WHERE item %param LIMIT 1"
cur.execute(sql_none_safe_generator(query,a))