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()
,這和它的工作。
請修復代碼格式化。 –