使用%s插入Python mysql连接器

2024-06-25 22:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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()

"Failed processing format-parameters; %s" % e)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; argument 2 to map() must support iteration


Tags: idformatdatalenmysql数字cursorparameters
2条回答

下面是一个在我的机器上工作的例子。

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

迟回答,但我想发布一些更好的代码。另外,最初的问题是使用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”是指“id的数量”)

相关问题 更多 >