【问题标题】:PyMySQL executemany INSERT List from variablePyMySQL 从变量中执行许多 INSERT 列表
【发布时间】:2019-11-28 22:31:39
【问题描述】:

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

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

【问题讨论】:

    标签: python-3.x insert pymysql executemany


    【解决方案1】:

    According to the pymysql docs executemany 函数需要一个序列序列或数据映射。

    你可以的

    data = list([(groupID, x) for x in membersList]) # Create a list of tuples
    

    应该可以解决问题。这是更新的代码sn-p-

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2017-12-05
        • 2018-02-15
        • 2020-02-20
        • 2018-03-31
        • 1970-01-01
        • 2016-09-02
        • 1970-01-01
        • 2020-10-09
        • 2017-08-28
        相关资源
        最近更新 更多