Python MySQLdb删除所有符合条件的行

2024-06-12 03:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我一直在看这篇文章(Python MySQLdb iterate through table),试图让它按我所希望的方式工作。你知道吗

我有一个users表和一个images表。你知道吗

usersenter image description here

images

enter image description here

在我的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
    

Tags: namefromidexecuteusernamewhereselectusers