我正在尝试使用 python 将 csv 文件插入到 mysql 中。我只是 mysql 的新程序员,所以我不确定是什么问题。这是我的代码:
file = csv.reader(file('20184329:2143.csv'))
for row in file:
sql_insert_table = ("""INSERT INTO STAGING(ADRESSE_1600 ,
ADRESSE_1601, ADRESSE_1602, ADRESSE_1603)
VALUES ('%s', '%d', '%d', '%s')""", row)
cursor.execute(sql_insert_table)
这是问题所在:
Traceback (most recent call last):
File "python_loaddata.py", line 22, in <module>
cursor.execute(sql_insert_table)
File "/usr/lib/python2.7/site-packages/MySQLdb/cursors.py", line 161, in execute
self.errorhandler(self, TypeError, m)
File "/usr/lib/python2.7/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
TypeError: must be string or read-only buffer, not tuple
您在这里遇到了两个问题,并且接近一个常见的安全漏洞。
看起来您正在尝试使用%
-style 替换来创建插入语句。我这么说是因为您在 SQL 字符串中引用了您的参数。这是一个非常非常糟糕的主意:如果有人输入他们的地址,例如,');DROP TABLE STAGING;--
那么您最终将执行他们的 SQL。相反,请使用 SQL 样式的占位符。那些看起来好像它们只是文字,比如VALUES (%s)
,而不是VALUES ('%s')
。
即使参数看起来像是将被 % 替换,就像您使用 Python 的%
运算符一样,但实际上并非如此。将使用实际值代替它们。所以,不要引用它们。
但是,您的错误的原因是要使用的语句和参数是cursor.execute
. 您目前将它们作为一个 2 长元组的单个参数传递。
这是一个固定版本:
sql_insert_table = """INSERT INTO STAGING(ADRESSE_1600 ,
ADRESSE_1601, ADRESSE_1602, ADRESSE_1603)
VALUES (%s, %s, %s, %s)"""
file = csv.reader(file('20184329:2143.csv'))
for row in file:
cursor.execute(sql_insert_table, row)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句