【发布时间】:2017-06-24 01:28:24
【问题描述】:
我正在尝试将函数与 mysql 和 python 一起使用,但出现错误: 我正在阅读一个文件 cnn.cvs 并且我想插入一个表 noticias 但我在代码中有错误。这里我分享一下代码:
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,你知道吗?
更新: 此问题已解决:
我用
cursor.executemany()
为此及其工作。
【问题讨论】:
-
请修正代码格式。