Python 3.x PyMySQL executemany从变量插入列表

Python 3.x PyMySQL executemany从变量插入列表,python-3.x,insert,pymysql,executemany,Python 3.x,Insert,Pymysql,Executemany,我试图使用pymysql在mysql表中插入一些数据,但失败了。 数据已经保存在变量中,所以我需要将它们传递给INSERT语句 这就是我目前正在尝试的 con = pymysql.connect(host='*.*.*.*', port=***, user='****', passwd='***', db='****') with con: cur = con.cursor() sql = ("INSERT INTO groupMembers (groupID, members

我试图使用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()
我试图传递的数据如下所示

groupID=G9gh472

membersList=[戴夫、鲍勃、迈克、比尔、科林]

列表的长度未知,可能会有所不同 生成的表我希望如下所示

| groupID | members |
+---------+---------+
| G9gh472 | Dave    |
| G9gh472 | Bob     |
| G9gh472 | Mike    |
| G9gh472 | Bill    |
| G9gh472 | Colin   |
在阅读其他人的答案的基础上,我尝试了一些不同的方法,但迄今为止,我所尝试的方法都没有奏效。
谢谢大家

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

生成序列的一种方法如下所示

productx,y返回x,y表示A中的x,y表示B中的y

product[groupId],成员返回序列中的元组

您可以参考以下代码-

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

传递给ExecuteMay函数的数据变量是元组 但函数需要序列/映射。 cursor.executemanyooperation,seq_of_params是函数签名。这就是你的代码不起作用的原因

生成序列的一种方法如下所示

productx,y返回x,y表示A中的x,y表示B中的y

product[groupId],成员返回序列中的元组

您可以参考以下代码-

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()
executemany函数需要数据的序列或映射序列

你能行

data = list([(groupID, x) for x in membersList]) # Create a list of tuples
这应该可以解决问题。下面是更新后的代码片段-

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()
executemany函数需要数据的序列或映射序列

你能行

data = list([(groupID, x) for x in membersList]) # Create a list of tuples
这应该可以解决问题。下面是更新后的代码片段-

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