Python MySQLdb删除满足条件的所有行

时间:2017-04-19 20:06:55

标签: python mysql

我想删除表中与特定值(userId

匹配的所有行

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

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

usersenter image description here

images

enter image description here

在我的python脚本中,我只引入了userName。首先是

  • 我需要使用传入的userId获取用户的userName。 (我有以下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
    

1 个答案:

答案 0 :(得分:0)

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