当我尝试连接到数据库时,在python中执行许多错误

时间:2017-06-24 01:28:25

标签: python database csv

我正在尝试使用mysql和python的函数,我收到错误: 我正在读取文件cnn.cvs,我想插入一个表消息,但我在代码中有错误。在这里,我分享代码:

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()

为此及其工作。

1 个答案:

答案 0 :(得分:1)

问题是从csv文件读取的每一行都作为csv.reader的字符串列表返回,您必须将列表row转换为元组,将代码更改为:

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

<强>更新

确保mysql数据库中有表noticias,例如:

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))