当我使用datetime从Mysql检索数据时,发生以下错误
TypeError:用于格式字符串的参数不足。这是我的代码,写在下面
temp1=datetime.strptime(date1, '%Y-%m-%d')
temp2=datetime.strptime(date2, '%Y-%m-%d')
rows1=exdb.getData("admin", "SELECT count(id) as total_count from client_onboard WHERE (video_datetime BETWEEN '%s' AND '%s');" % (temp1) %(temp2))
答案 0 :(得分:0)
The answer in this question thread should solve your problem。
您应该改用.format()
。
答案 1 :(得分:0)
您必须使用元组进行字符串格式设置:
from datetime import datetime
date1 = "2018-01-01"
date2 = "2018-02-01"
# Date parsing
temp1 = datetime.strptime(date1, '%Y-%m-%d')
temp2 = datetime.strptime(date2, '%Y-%m-%d')
rows1 = exdb.getData("admin",
"""SELECT count(id) as total_count from client_onboard
WHERE (video_datetime BETWEEN '%s' AND '%s');""" % (temp1, temp2)
)
对于输入不受信任的SQL查询,您应该不使用字符串格式-例如来自用户。这使您的代码对于SQL injection来说很脆弱。 Python DBAPI的cursor
对象可以为您处理此问题,例如:
cur.execute("SELECT * FROM platforms WHERE language = %s;", (platform,))