【问题标题】:Python mysql connector insert with %s使用 %s 插入 Python mysql 连接器
【发布时间】:2013-03-13 13:46:14
【问题描述】:

我正在尝试使用 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 必须支持迭代

【问题讨论】:

  • 哎呀。磨损的桌子。正确的是: cursor.execute('''CREATE TABLE anzahlids( idnummer INT )''') 在代码中它是正确的。
  • 请发一个idset中的数据示例
  • idset 是一个 id 列表。这些 id 是数字。但我想将len(idset) 插入到数据库中。
  • 插入语句与表定义不匹配。请参阅我的答案中的示例。

标签: python mysql mysql-python mysql-connector


【解决方案1】:

迟到的答案,但我想发布一些更好的代码。此外,最初的问题是使用 MySQL 连接器/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 连接器/Python(与 MySQLdb 不同),您必须确保自己正在提交。

(非德语人士注意:“anzahlids”表示“number_of_ids”)

【讨论】:

    【解决方案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()
    

    【讨论】:

    • 谢谢,但这会产生:raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '[100])' at line 但我们似乎越来越近了......
    • 我的错误...我更改了答案以反映 cursor.execute many 所需的参数类型。
    • 啊,现在是:values.append(fmt % self._process_params(params)) TypeError: not all arguments converted during string formatting 但再次感谢!
    • 请张贴 idset 的打印输出
    • idset 是一个 id 列表。这些 id 是数字。但我想将len(idset) 插入到数据库中。
    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 2013-02-07
    • 2013-06-07
    • 1970-01-01
    • 2018-10-25
    • 2020-11-06
    • 2021-09-10
    • 2021-06-07
    相关资源
    最近更新 更多