2015-09-07 92 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))