PyMySQL执行许多从变量

时间:2019-07-20 00:06:32

标签: 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) 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   |

我在阅读其他答案的基础上尝试了一些变体,但到目前为止我没有尝试过。 谢谢大家

2 个答案:

答案 0 :(得分:0)

您要传递给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()

答案 1 :(得分:0)

According to the pymysql docs 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()