【发布时间】:2017-01-25 04:34:06
【问题描述】:
executemany 返回以下错误时遇到问题
(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 'IBM'',''1998-01-02 09:30:00'',''104.5'',''104.5'',''104.5'',''104.5'',''67000'')' at line 2")
有趣的是,我通过简单的执行命令成功地使用了完全相同的语法。为了演示,此代码将使用 execute 成功添加一条记录,但是使用与 execute many 相同的语法会返回上述错误。有什么见解吗?
import MySQLdb
from MySQLdb import *
import datetime
db1 = MySQLdb.connect(host="127.0.0.1",user="root",passwd="password")
c = db1.cursor()
c.execute("use securities_master")
testdata = [('IBM', datetime.datetime(1998, 1, 2, 9, 30), '104.5', '104.5', '104.5', '104.5', '67000'),
('IBM', datetime.datetime(1998, 1, 2, 9, 31), '104.375', '104.5', '104.375', '104.375', '10800'),
('IBM', datetime.datetime(1998, 1, 2, 9, 32), '104.4375', '104.5', '104.375', '104.5', '13300'),
('IBM', datetime.datetime(1998, 1, 2, 9, 33), '104.4375', '104.5', '104.375', '104.375', '16800'),
('IBM', datetime.datetime(1998, 1, 2, 9, 34), '104.375', '104.5', '104.375', '104.375', '4801'),
('IBM', datetime.datetime(1998, 1, 2, 9, 35), '104.4375', '104.5', '104.375', '104.375', '23300'),
('IBM', datetime.datetime(1998, 1, 2, 9, 36), '104.4375', '104.4375', '104.375', '104.4375', '2600'),
('IBM', datetime.datetime(1998, 1, 2, 9, 37), '104.375', '104.375', '104.375', '104.375', '2800'),
('IBM', datetime.datetime(1998, 1, 2, 9, 38), '104.375', '104.4375', '104.375', '104.4375', '11101')]
sql = """INSERT IGNORE INTO stocks_datamine (symbol_id,price_date,open_price,high_price,low_price,close_price,volume) VALUES('%s','%s','%s','%s','%s','%s','%s')"""
for record in testdata[:1]:#test insert on one record
sql_statement = sql%record
c.execute(sql_statement)
db1.commit()
print 'success!'
#same sql statement just for multiple records - returns error :(
c.executemany(sql, testdata)
db1.commit()
【问题讨论】:
-
不要在 SQL 中为
%s加上引号。该库在执行替换时会添加引号,因此您最终会得到两个引号。 -
好的,我删除了 %s 周围的引号。同样的错误,(1064,“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本对应的手册以获取正确的语法在第 1 行的 '09:30:00,104.5,104.5,104.5,104.5,67000)' 附近使用")
-
你能用不带引号的最新查询更新问题吗?
-
很奇怪。现在看起来它没有添加任何引号。我不知道为什么它只会在查询已经有引号时添加引号,而不是在没有引号时添加它们。
标签: python mysql-python