【问题标题】:Issue getting csv data into mysql table with python and mysqldb使用 python 和 mysqldb 将 csv 数据导入 mysql 表的问题
【发布时间】:2013-05-22 08:09:21
【问题描述】:

我一直在使用这个 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")

【问题讨论】:

    标签: python mysql csv mysql-python


    【解决方案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])
    

    【讨论】:

    • 我有一个包含许多列的 csv 文件,我想将两个导入一个表,十个导入另一个,十个导入另一个。我怎么能像这样修改代码以具有选择性?
    猜你喜欢
    • 2019-07-24
    • 2020-05-06
    • 2013-07-12
    • 1970-01-01
    • 2011-08-06
    • 2011-01-11
    • 2020-08-06
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多