我正在尝试使用 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()
我试图传递的数据如下所示......
组 ID = G9gh472
成员列表 = [戴夫、鲍勃、迈克、比尔、科林]
列表的长度未知并且可能会有所不同
结果表我想看起来像这样......
| groupID | members |
+---------+---------+
| G9gh472 | Dave |
| G9gh472 | Bob |
| G9gh472 | Mike |
| G9gh472 | Bill |
| G9gh472 | Colin |
我根据阅读其他人的答案尝试了一些变体,但到目前为止我尝试过的都没有效果。
谢谢大家
根据 pymysql 文档 https://pymysql.readthedocs.io/en/latest/modules/cursors.htmlexecutemany 函数需要数据的序列或映射的序列。
你可以做
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)