【问题标题】:Python MySQLdb delete all rows that meet conditionPython MySQLdb删除所有满足条件的行
【发布时间】:2017-09-16 05:44:28
【问题描述】:

我想删除表中与某个值匹配的所有行 (userId)

我一直在查看这篇文章 (Python MySQLdb iterate through table),试图让它按照我想要的方式工作。

我有一个users 表和一个images 表。

users:

images:

在我的 python 脚本中,我只提取了用户名。所以首先

  • 我需要使用传入的userName 获取用户的userId。 (我有以下SELECT 语句,但不知道如何将结果分配给变量)

    import MySQLdb
    
    dbb = MySQLdb.connect(host="ipaddress",     
    user="root",    
    passwd="myPassword",
    db="myDatabase")
    
    user_name = "user"
    
    cursor = dbb.cursor()    
            cursor.execute("""SELECT userId FROM users WHERE userName ='%s'""" (user_name))
    
    var users_id = 0 // need to assign users_id to the selected userId from above code
    

然后

  • 我需要遍历images 表并删除对应userId 的所有行

    cursor2 = dbb.cursor()    
    cursor2.execute("""SELECT FROM images WHERE userId='%s'""" (users_id))  
    for cursor2: //don't think this is right...
    //DELETE all rows with matching users_id
    

【问题讨论】:

  • 什么python脚本?您还没有发布任何代码。
  • @ScottHunter 补充了我能做到的

标签: python mysql


【解决方案1】:

您可以遍历SELECT 语句生成的行,就像execute 方法返回行列表一样。

【讨论】:

    猜你喜欢
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 2011-11-02
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多