ProgrammingError:字符串格式化过程中的参数数量错误

Bou*_*h10 2 python mysql python-2.7

我正在尝试将列表中的一些数据主动放入表中的数据库中polls_ip.然而,似乎存在一些争论的问题可能是由于我想要放入的数据类型.

如果你想看看我的代码中有用的部分:

fin_flag = ( tcp.flags & dpkt.tcp.TH_FIN ) != 0
rst_flag = ( tcp.flags & dpkt.tcp.TH_RST ) != 0

if fin_flag or rst_flag:
    src_ip2 = socket.inet_ntoa(ip.src)
    dst_ip2 = socket.inet_ntoa(ip.dst)
    for element in liste:
        if element == (src_ip2+" "+dst_ip2) or element == (dst_ip2+" "+src_ip2):
            liste.remove(element)

            cursor.execute("INSERT INTO polls_ip (Ip) VALUES (%s)", (element))
Run Code Online (Sandbox Code Playgroud)

问题可能来自内线cursor.execute 看看输出:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "scriptbdd.py", line 134, in run
    self.p.dispatch(0, PieceRequestSniffer.cb)
  File "scriptbdd.py", line 120, in cb
    cursor.execute("INSERT INTO polls_ip (Ip) VALUES (%s)", (element))
  File "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 310, in execute
    "Wrong number of arguments during string formatting")
ProgrammingError: Wrong number of arguments during string formatting
Run Code Online (Sandbox Code Playgroud)

即使陷入昏迷,也会出现(element,))另一个问题:

root@debian:/home/florian/Documents/mysite/polls# python scriptbdd.py 
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "scriptbdd.py", line 132, in run
    self.p.dispatch(0, PieceRequestSniffer.cb)
  File "scriptbdd.py", line 120, in cb
    cursor.execute("INSERT INTO polls_ip (Ip) VALUES (%s)", (element,))
  File "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 314, in execute
    res = self.db().protocol.cmd_query(stmt)
InterfaceError: Failed executing the operation; 'NoneType' object has no attribute 'cmd_query'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 9

你忘了逗号:

cursor.execute("INSERT INTO polls_ip (Ip) VALUES (%s)", (element,))
#                                              add a comma here ^
Run Code Online (Sandbox Code Playgroud)

这使得第二个参数成为具有一个元素的元组,而不仅仅是一个值.

如果您发现它更容易使用,您可以将第二个参数设为列表而不是元组:

cursor.execute("INSERT INTO polls_ip (Ip) VALUES (%s)", [element])
Run Code Online (Sandbox Code Playgroud)

元组是使用逗号形成的(只有在消除其他用途的逗号时才需要括号),而列表是使用[..]语法形成的.

您的第二个错误表明您的数据库连接已关闭; 如果您的数据库连接存储在已清理的本地某处,则无法传递光标.例如,您无法在函数中创建数据库连接并仅返回游标; 在您使用游标之前,将清除引用连接的局部变量并关闭连接.请参阅为什么Python不会从函数返回我的mysql-connector游标?