MySQL TypeError:格式字符串的参数不足

时间:2018-08-10 08:40:44

标签: python mysql mysql-workbench

当我使用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)) 

2 个答案:

答案 0 :(得分:0)

答案 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查询,您应该使用字符串格式-例如来自用户。这使您的代码对于SQL injection来说很脆弱。 Python DBAPI的cursor对象可以为您处理此问题,例如:

cur.execute("SELECT * FROM platforms WHERE language = %s;", (platform,))