如何在Python中无错误地将csv写入mysqldb?

时间:2017-07-26 11:49:51

标签: python csv mysql-python

我有一个csv文件,我想用Python 2.7写入MYSQLdb。 我已经用另一个csv文件做了这个,它工作正常,但在这里我得到一个关于query.cursor的错误消息?!

错误讯息:

Traceback (most recent call last):
  File "C:/Python27/air18.py", line 84, in <module>
    cursor.execute(query)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 221, in execute
    if not self._defer_warnings: self._warning_check()
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 107, in _warning_check
    warnings = self._get_db().show_warnings()
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 371, in show_warnings
    self.query("SHOW WARNINGS")
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 282, in query
    _mysql.connection.query(self, query)
ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

这是我的代码:

connection = MySQLdb.connect(host='localhost',
    user='root',
    passwd='1234',
    db='database')
cursor = connection.cursor()
query = """ 
   CREATE TABLE `airline` (
  `A` varchar(100) DEFAULT NULL,
  `B` varchar(100) DEFAULT NULL,
  `C` varchar(100) DEFAULT NULL,
  `D` varchar(100) DEFAULT NULL,
  `E` varchar(100) DEFAULT NULL,
  `F` varchar(100) DEFAULT NULL,
  `G` varchar(100) DEFAULT NULL,
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8"""
cursor.execute(query)
connection.commit()
cursor.close()

connection = MySQLdb.connect(host='localhost',
    user='root',
    passwd='1234',
    db='database')
cursor = connection.cursor()
query = """ load data local infile 'C:/Python27/output.csv' 
into table airline
character set latin1
fields terminated by ';'
enclosed by '"'
lines terminated by '\r\n';
ignore 1 lines;
"""
cursor.execute(query)
connection.commit()
cursor.close()

“创建表”部分正在运行,但第二部分当我想上传它时csv文件无效。

我的csv文件:

"apple apricot";" avocado";"blackcurrant (fruit)-";"blackberry";"blueberry (fruit) ";"";"lemon lime"
"quince pear";" banana";"papaya (fruit)-";"orange";"passion fruit (fruit) ";"";"pineapple watermelon"

0 个答案:

没有答案