【问题标题】:How to use MySQL executemany to update list of lists in Python?如何使用 MySQL executemany 更新 Python 中的列表列表?
【发布时间】:2012-05-19 06:29:48
【问题描述】:

我有一个列表列表:myList = [[123, 345], [23, 45], [54, 34]]

我想做这样的事情:

cursor.executemany("update tablename set flag = 'yes' where id = %s and officeid = %s", myList)

我搜索了这个并没有找到解决方案。如果永远不会实现,那么在不必循环遍历列表中的所有元素的情况下,有什么更好的更新语句?

【问题讨论】:

    标签: python mysql list executemany


    【解决方案1】:
    myTuples = tuple(map(tuple, myList))
    
    cursor.execute("update tablename set flag = 'yes' \
    where (id, officeid) in " + str(myTuples))
    

    【讨论】:

    • 它说:TypeError: executemany() 正好需要 3 个参数(给定 2 个),但 execute() 工作得很好!
    • 谢谢 - 修改了上面的解决方案。 :)
    • 如果 flag 是元组中的值而不是常量“yes”,我们将如何修改它?我们可以这样做: cursor.execute("update tablename set flag = %s \ where (id, officeid) in " + str(myTuples)) 其中 myTuple 可能是 ('nope', 21, 32) .. 这里有什么指针吗?谢谢!
    【解决方案2】:
    update tablename set flag = 'yes' 
    WHERE (id,officeid) IN ((123,345), (23,45), (54,34));
    

    【讨论】:

    • 我可以知道列表列表的 Python 等效项吗?
    • @ThinkCode:对不起,我不熟悉 Python。查询在Mysql中有效,但是我不知道如何在Python中传递这些参数。
    • 列表列表的 Python 等效项是列表列表。例如。问题中的myList 是一个列表列表。如果你把它变成一个元组的元组,它将是((123,345), (23,45), (54,34)),并且用“%s”插入它会按照 MySQL 解释器的预期工作,尽管如果项目来自用户输入,它看起来像是 SQL 注入的场所。
    猜你喜欢
    • 2020-12-11
    • 2013-08-17
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多