我正在打开一个文本文件并尝试将其写入SQL数据库。
import mysql.connector
import sys
import mysql
f = open('norepeats.txt', 'r')
def sniffertodatabase(f):
for line in f:
linestrip = line.strip()
IP = linestrip
cnx = mysql.connector.connect(user='', password='', host='localhost', database='snifferdb')
cur = cnx.cursor()
#print IP
insert_stmt = (
"INSERT INTO SNIFFERDBIPs (IP)"
"VALUES (%s)"
)
data = ('IP')
cur.execute(insert_stmt, data)
#cur.execute("INSERT INTO SNIFFERDBIPs (IP)" "VALUES (%s), (IP)")
#cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar'))
cnx.commit()
cnx.close()
sniffertodatabase(f)
我得到的错误是:
Traceback (most recent call last):
File "snifferdatabase.py", line 26, in <module>
sniffertodatabase(f)
File "snifferdatabase.py", line 19, in sniffertodatabase
cur.execute(insert_stmt, data)
File "build/bdist.linux-x86_64/egg/mysql/connector/cursor.py", line 480, in execute
mysql.connector.errors.ProgrammingError: Wrong number of arguments during string formatting
如何解决此错误?
答案 0 :(得分:6)
你有data=('IP')
。即使你把它放在括号中,它也不会被视为元组。见:
>>> type(('IP'))
<type 'str'>
>>> type(('IP',))
<type 'tuple'>
>>>
因此,您需要将data=('IP')
更改为data=('IP',)
答案 1 :(得分:0)
您也可以使用列表而不是元组
data = ['IP']