Python MySQL 连接器使用 %s 插入

2 投票
2 回答
9871 浏览
提问于 2025-04-17 20:05

我正在尝试使用Python的MySQLConnector把一个包含数字的集合添加到我的MySQL数据库中。我可以手动添加数据,但使用%s的这个表达式却不行。我尝试了几种不同的写法,但文档里的内容在我这儿都没用。你可以看到,表格已经建立好了:

#Table erstellen:
#cursor.execute('''CREATE TABLE anzahlids( tweetid INT  )''')

这是我的代码和错误信息:

print len(idset)
    id_data = [
        len(idset)
    ]
    print id_data
    insert = ("""INSERT INTO anzahlids (idnummer) VALUES (%s)""")
    cursor.executemany(insert, id_data)
    db_connection.commit()

"处理格式参数失败; %s" % e)
mysql.connector.errors.ProgrammingError: 处理格式参数失败;传给map()的参数2必须支持迭代

2 个回答

3

虽然我来得有点晚,但我想分享一些更好的代码。此外,最初的问题是关于使用 MySQL Connector/Python 的。

这里使用 executemany() 是不对的。executemany() 方法需要一个元组的序列,比如说 [ (1,), (2,) ]。

对于当前的问题,executemany() 实际上并没有用,应该使用 execute() 方法:

cur.execute("DROP TABLE IF EXISTS anzahlids")
cur.execute("CREATE TABLE anzahlids (tweetid INT)")

some_ids = [ 1, 2, 3, 4, 5]
cur.execute("INSERT INTO anzahlids (tweetid) VALUES (%s)",
            (len(some_ids),))
cnx.commit()

而且在使用 MySQL Connector/Python 时(与 MySQLdb 不同),你需要确保你在提交数据。

(给不懂德语的人一个提示:'anzahlids' 的意思是 'number_of_ids')

0

下面是一个在我电脑上能正常运行的例子。

import MySQLdb
db = MySQLdb.connect(host="localhost", user="stackoverflow", passwd="", db="stackoverflow")
cursor = db.cursor()
try:
    sql = 'create table if not exists anzahlids( tweetid int ) ; '
except:
    #ignore
    pass

sql = ("""INSERT INTO anzahlids (tweetid) VALUES (%s)""")
data = [1,2,3,4,5,6,7,8,9]
length = [len(data)]
cursor.executemany(sql,length)
db.commit()

如果idset是一个单一的值,你可以使用

sql = ("""INSERT INTO anzahlids (tweetid) VALUES (%s)""") % len(idset)
cursor.execute(sql)
db.commit()

撰写回答