2014-11-21 41 views
2

我打開一個文本文件並試圖將其寫入SQL數據庫。mysql.connector.errors.ProgrammingError:在字符串格式化過程中參數數量錯誤

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

你'data'應'( 'IP')';這是_str_現在,但你需要_tuple_ – dazedconfused 2014-11-21 01:08:35

+0

我沒有作爲答覆發佈,所以這是沒問題的;順便說一句,你正在創建和關閉文件中每一行的連接,你應該只做一次,這會更好 – dazedconfused 2014-11-21 01:42:52

回答

6

您有data=('IP')。即使你把它放在括號內,它也不會被當作元組來處理。看到這一點:

>>> type(('IP')) 
<type 'str'> 
>>> type(('IP',)) 
<type 'tuple'> 
>>> 

所以,你需要改變你的data=('IP')data=('IP',)

0

你也可以使用一個列表,而不是一個元組的方式,你可以做

data = ['IP'] 
相關問題