MySQLdb Executemany错误

时间:2016-09-16 21:08:02

标签: python mysql-python

我遇到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的SAME语法会返回上述错误。有什么见解吗?

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()

2 个答案:

答案 0 :(得分:0)

你在for循环中所做的是错误的。 您正在使用sql_statement = sql%record将查询格式化为字符串,这不是正确的方法。 您正在构建一个查询,这就是您使用MySQLdb的目的。

您需要做的是:

# remove quotes from the query
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:
    # let MySQLdb to handle parameters.
    c.execute(sql_statement, record)
    db1.commit()

答案 1 :(得分:0)

问题出在sql查询中,您为%s添加了引号(删除它们):

sql = """INSERT ... VALUES(%s, %s, %s, %s, %s, %s, %s)