python - 使用 python 和 mysqldb 将 csv 数据获取到 mysql 表中

标签 python mysql csv mysql-python

我已经和这段 python 代码斗争了一段时间,当我尝试执行时遇到了各种错误。

import csv
import MySQLdb
# open the connection to the MySQL server.
# using MySQLdb
mydb = MySQLdb.connect(host='myhostinfo',
user='me',
passwd='mypw',
db='thedatabase')
cursor = mydb.cursor()
# read the presidents.csv file using the python
# csv module http://docs.python.org/library/csv.html
csv_data = csv.reader(file('CHN-mod.csv'))
# execute the for clicle and insert the csv into the
# database.
for row in csv_data:

    cursor.execute('INSERT INTO INDICATORS(INDICATORNAME, \
            , INDICATORCODE)' \
            'VALUES(%s, %s)',  row)
#close the connection to the database.
cursor.close()
print "Import to MySQL is over"

我的代码在在线 python 验证器中验证,但出现错误:

Traceback (most recent call last):
  File "importdata.py", line 23, in <module>
    'VALUES(%s, %s)' , row)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 201, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaultterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' INDICATORCODE)VALUES('Indicator Name', 'Indicator Code'>' at line 1")

最佳答案

In [1]: 'INSERT INTO INDICATORS(INDICATORNAME, \
            , INDICATORCODE)' \
            'VALUES(%s, %s)'
Out[1]: 'INSERT INTO INDICATORS(INDICATORNAME,             , INDICATORCODE)VALUES(%s, %s)'

INDICATORNAME 后有两个逗号。


改用多行字符串:

cursor.execute('''INSERT INTO INDICATORS (INDICATORNAME, INDICATORCODE)
                  VALUES (%s, %s)''', row)

它更容易阅读,并且会避免您遇到的问题。 MySQLdb 可以很好地解析字符串(尽管有空格)。


要将每一行的一部分插入到三个不同的表中,您可以这样做:

insert_indicators = '''INSERT INTO INDICATORS (INDICATORNAME, INDICATORCODE)
                       VALUES (%s, %s)'''
insert_foo = 'INSERT INTO FOO (...) VALUES (%s)' % (','.join(['%s']*10))
insert_bar = 'INSERT INTO BAR (...) VALUES (%s)' % (','.join(['%s']*10))

for row in csv_data:
    cursor.execute(insert_indicators, row[:2])
    cursor.execute(insert_foo, row[2:12])
    cursor.execute(insert_bar, row[12:22])

关于python - 使用 python 和 mysqldb 将 csv 数据获取到 mysql 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773677/

相关文章:

python - 使用 ElementTree 库转义 xml 属性中的 python 保留字

python - 如何从一行之间删除换行符而不从行尾删除换行符python?

python - 使用 NLTK 删除停用词时对象没有属性

ssh - Mysql 恢复 1GB db 错误 2006 BLOB 文件

jquery - 使用 Jquery Bootgrid 的 Asp.Net MVC 应用程序不显示任何结果

mysql - 如何在ADO.NET DataAdapter.InsertCommand上检索行ID

Python 在写入 CSV 文件之前检查列数据是否存在

php - 确定所有 CSV 列的最小值和最大值

python - 结合两个 warpAffine,移动和旋转图像

python - 如何在 iPython Notebook> 中重用绘图布局?