2017-06-24 28 views
0

我想使用函數與mysql和python,我得到錯誤: 我正在閱讀文件cnn.cvs,我想插入一個表noticias,但我在代碼中有錯誤。在這裏我共享代碼:得到錯誤,在python中執行很多時,當我試圖連接到數據庫

import csv 
import MySQLdb 
mydb = MySQLdb.connect(host='localhost', 
user='root', 
passwd='password', 
db='cnn') 
cursor = mydb.cursor() 
f = open('cnn.csv', 'r') 
csv_data = csv.reader(f) 
for row in csv_data: 
cursor.execute('INSERT INTO noticias(title, \ 
link, pubDate)' \ 
'VALUES("%s", "%s", "%s")', 
row) 
#close the connection to the database. 
mydb.commit() 
cursor.close() 
print ("Done") 

,當我執行這就是結果:

C:\Users\SoriyAntony\AppData\Local\Programs\Python\Python36-32\python.exe 
"C:\Program Files\JetBrains\PyCharm Community Edition 
2017.1.4\helpers\pydev\pydevd.py" --multiproc --qt-support --client 127.0.0.1 --port 59726 --file C:/Users/SoriyAntony/PycharmProjects/cnnbd/cnnbd 
pydev debugger: process 10368 is connecting 

Connected to pydev debugger (build 171.4694.38) 
Traceback (most recent call last): 
File "C:\Users\SoriyAntony\AppData\Local\Programs\Python\Python36- 
32\lib\site-packages\MySQLdb\cursors.py", line 238, in execute 
query = query % args 
TypeError: not enough arguments for format string 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
File "C:\Program Files\JetBrains\PyCharm Community Edition 
2017.1.4\helpers\pydev\pydevd.py", line 1591, in <module> 
globals = debugger.run(setup['file'], None, None, is_module) 
File "C:\Program Files\JetBrains\PyCharm Community Edition 
2017.1.4\helpers\pydev\pydevd.py", line 1018, in run 
pydev_imports.execfile(file, globals, locals) # execute the script 
File "C:\Program Files\JetBrains\PyCharm Community Edition 
2017.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile 
exec(compile(contents+"\n", file, 'exec'), glob, loc) 
File "C:/Users/SoriyAntony/PycharmProjects/cnnbd/cnnbd", line 17, in 
<module> 
row) 
File "C:\Users\SoriyAntony\AppData\Local\Programs\Python\Python36- 
32\lib\site-packages\MySQLdb\cursors.py", line 240, in execute 
self.errorhandler(self, ProgrammingError, str(m)) 
File "C:\Users\SoriyAntony\AppData\Local\Programs\Python\Python36- 
32\lib\site- 
packages\MySQLdb\connections.py", line 52, in defaulterrorhandler 
raise errorclass(errorvalue) 
_mysql_exceptions.ProgrammingError: not enough arguments for format string 

Process finished with exit code 1 

我使用python 3.6,的任何想法?

UPDATE: 這個問題解決:

我用

cursor.executemany() 

,這和它的工作。

+0

請修復代碼格式化。 –

回答

1

的問題是,從CSV文件中讀取每一行返回爲csv.reader字符串列表,您必須將名單row轉換成元組,你的代碼更改爲:

cursor.execute('INSERT INTO noticias(title, \ 
link, pubDate)' \ 
'VALUES("%s", "%s", "%s")', 
tuple(row)) 

更新:

確保有表noticias在你的MySQL數據庫,例如:

create table noticias (title Varchar(255),link varchar(255),pubDate varchar(255)) 

cnn.csv文件包含空行,當讀它,會出現空列表,你必須放棄它,這樣的改變你的for循環:

for row in csv_data: 
    if len(row)!=0: 
     cursor.execute('INSERT INTO noticias(title, link, pubDate) VALUES("%s", "%s", "%s")',tuple(row)) 
相關問題