【发布时间】:2017-08-27 08:27:27
【问题描述】:
我是 MySQL 和 Python 的新手,我正在尝试使用 python 将一个简单的 csv 文件中的单列浮点数据读取到本地 MySQL 表中,但它反复抛出一些错误。在敲击键盘几个小时后,我纠正了一些语法错误,现在我被困在这里了。任何帮助将不胜感激。也请原谅我在这里的问题格式,因为这是我第一次。
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='test1')
cursor = mydb.cursor()
csv_data = csv.reader(file('csv1.csv'))
for row in csv_data:
cursor.execute("INSERT INTO log1(speed) values( %s )" %row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
这是显示的错误:
Traceback (most recent call last):
File "test2.py", line 13, in <module>
cursor.execute("INSERT INTO log1(speed) values( %s )" %row)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise 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 '['85.26'] )' at line 1")
csv 文件包含如下某些测试数据:
85.26
72.67
80.12
99.86
65.64
我的数据库似乎具有以下结构:
+-------+---------+
| speed | test_id |
+-------+---------+
| 98.86 | 1 |
| 88.86 | 2 |
| 78.86 | 3 |
+-------+---------+
其中speed是需要从csv文件中读取的字段,test_id是自增主键
编辑
根据 Visweswaran 的建议,我已将代码更改如下:
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='test1')
cursor = mydb.cursor()
csv_data = csv.reader(file('csv1.csv'))
for row in csv_data:
cursor.execute("INSERT INTO log1(speed) values( %s )" %row[0])
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
现在这似乎已经修复了 Type: List 错误,但现在我收到以下错误:
File "test2.py", line 12, in <module>
cursor.execute("INSERT INTO log1(speed) values( %s )" %row[0])
IndexError: list index out of range
我很确定我错过了一些基本的东西并且做了一些非常愚蠢的事情,但是先生您的支持将非常有帮助。
【问题讨论】:
-
您收到的错误消息是不言自明的,即您的查询中有错误。
-
感谢您的快速回复。请原谅我,但我在这里完全不知所措。你能指出错误到底是什么吗?正如我所说,我对 MySQL 完全陌生,所以我真的需要一些帮助。
-
你能描述一下你的表结构吗,比如os speed和test_id的类型是什么
-
speed 应该是 float 类型,而不是 null。 test_id 应该是 unsigned int,不为 null,auto_increment,主键
-
查询似乎没问题,但我认为row是一个列表。使用 print type(row) 查看是否为列表。