我正在尝试从python插入一些值到MySQL,我收到以下错误。
Python中的连接和代码:
conn = MySQLdb.connect(host="localhost",user="lpr",passwd="B1ack53@",db="lpr")
c=conn.cursor()
c.execute("INSERT INTO liccaptured(realtime, proctime, plate, confid, uuid) VALUES (%s,%s,%s,%s,%s)", realtime,proctime,plate,confid,uuid)
错误信息:
c.execute("INSERT INTO liccaptured(realtime, proctime, plate, confid, uuid) VALUES (%s,%s,%s,%s,%s)", realtime,proctime,plate,confid,uuid)
TypeError: execute() takes at most 3 arguments (7 given)
我试着寻找类似的错误,不能找出我做错了什么。
您遇到的错误来自于您将cursor.execute
方法视为接受可变数量参数的方法:
c.execute(operation, arg1, arg2, ..., argn) # won't work
execute
只接受固定数量的参数。SQL语句本身的参数作为一个元组参数传入:
my_args = (arg1, arg2, ..., argn)
c.execute(operation, my_args) # this will work
c.execute(operation, (arg1, arg2, ..., argn)) # just the same as above
错误信息说明一切:函数execute
最多有3个参数,但你用7个参数调用它。所以你只需要用3个参数正确地调用它。
根据文档,execute
函数的语法如下:
cursor.execute(operation, params=None, multi=False)
-
operation
是SQL查询字符串 -
params
是参数数组 -
multi
是布尔标志
没有正确传递元组字符串操作符。因此,c.execute()
假定有多个参数。简单地说,将%
放在没有逗号的string后面,并将所有变量用圆括号
c.execute("INSERT INTO liccaptured (realtime, proctime, plate, confid, uuid)
VALUES (%s,%s,%s,%s,%s)" % (realtime,proctime,plate,confid,uuid))
或者,考虑使用字符串格式:
c.execute("INSERT INTO liccaptured (realtime, proctime, plate, confid, uuid)
VALUES ({0},{1},{2},{3},{4})".format(realtime,proctime,plate,confid,uuid))