2015-09-07 121 views
1

我想从python插入一些值到MySQL,我收到以下错误。Python插入到mysql

连接和代码在Python:

conn = MySQLdb.connect(host="localhost",user="lpr",passwd="[email protected]",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) 

我试图寻找类似的错误,无法弄清我做错了。任何帮助表示感谢。

回答

1

您正在运行到错误来自您正在处理cursor.execute方法是一种能够接受可变数目的参数的事实:

c.execute(operation, arg1, arg2, ..., argn) # won't work 

execute只接受的参数固定数量虽然。在SQL语句本身的PARAMATERS形式传入一个参数是一个元组:

my_args = (arg1, arg2, ..., argn) 
c.execute(operation, my_args)     # this will work 
c.execute(operation, (arg1, arg2, ..., argn)) # just the same as above 
0

错误消息称一切:功能execute至多有3个参数,但你与7个参数调用它。所以你只需要用3个参数正确地调用它。

根据documentationexecute函数的语法如下:

cursor.execute(operation, params=None, multi=False)

  • operation是SQL查询作为字符串
  • params是参数数组
  • multi是布尔标志
0

您没有正确传递元组字符串运算符。因此,c.execute()假定有多个参数。简单地说,将%只是字符串没有逗号后,和包中的所有变量括号

c.execute("INSERT INTO liccaptured (realtime, proctime, plate, confid, uuid) \ 
      VALUES (%s,%s,%s,%s,%s)" % (realtime,proctime,plate,confid,uuid)) 

另外,可以考虑使用string format

c.execute("INSERT INTO liccaptured (realtime, proctime, plate, confid, uuid) \ 
      VALUES ({0},{1},{2},{3},{4})".format(realtime,proctime,plate,confid,uuid))