PyMySQL 从变量执行许多 INSERT 列表

Pro*_*ogD 4 insert executemany python-3.x pymysql

我正在尝试使用 pymysql 在 mysql 表中插入一些数据,但失败了。数据已经保存在变量中,因此我需要将它们传递给 INSERT 语句。

这就是我目前正在尝试的......

con = pymysql.connect(host='*.*.*.*', port=***, user='****', 
passwd='***', db='****')
with con:
    cur = con.cursor()
    sql = ("INSERT INTO groupMembers (groupID, members) VALUES (%s, %s)")
    data = (groupID, (x for x in membersList))
    cur.executemany(sql, data)
    con.commit()
    con.close()
Run Code Online (Sandbox Code Playgroud)

我试图传递的数据如下所示......

组 ID = G9gh472

成员列表 = [戴夫、鲍勃、迈克、比尔、科林]

列表的长度未知,并且可能会改变结果表,我希望看起来像这样......

| groupID | members |
+---------+---------+
| G9gh472 | Dave    |
| G9gh472 | Bob     |
| G9gh472 | Mike    |
| G9gh472 | Bill    |
| G9gh472 | Colin   |
Run Code Online (Sandbox Code Playgroud)

我根据阅读其他人的答案尝试了一些变体,但到目前为止我尝试过的都没有效果。谢谢大家

小智 6

根据 pymysql 文档, executemany 函数需要数据的序列或映射的序列。

你可以做

data = list([(groupID, x) for x in membersList]) # Create a list of tuples
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题。这是更新后的代码片段 -

con = pymysql.connect(host='*.*.*.*', port=***, user='****', 
passwd='***', db='****')
with con:
    cur = con.cursor()
    sql = ("INSERT INTO groupMembers (groupID, members) VALUES (%s, %s)")
    data = list([(groupID, x) for x in membersList]) # Create a list of tuples
    cur.executemany(sql, data)
    con.commit()
    con.close()
Run Code Online (Sandbox Code Playgroud)


gpk*_*k27 5

您传递给executemany函数的数据变量是一个元组,但函数需要一个序列/映射。 cursor.executemany(operation, seq_of_params)是函数签名。这就是您的代码不起作用的原因。

产生序列的一种方法如下。

product(x,y) returns ((x,y) for x in A for y in B)

product([groupId], members)返回元组的元组(序列)。

你可以参考下面的代码——

import itertools

    with con.cursor() as cur: # a good practice to follow
        sql = ("INSERT INTO test (id, memb) VALUES (%s, %s)")
        cur.executemany(sql, itertools.product([groupId], members)) # the change needed
    con.commit()
Run Code Online (Sandbox Code Playgroud)