2017-04-19 83 views
-1

所有行我要刪除表中符合特定值的所有行(userId的Python MySQLdb的刪除符合條件

我一直在看這篇文章(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 
    
所有行
+0

什麼python腳本?你還沒有發佈任何代碼。 –

+0

@ScottHunter新增了我能做的 – velkoon

回答

0

您可以遍歷SELECT語句生成的行,就好像execute方法返回行列表一樣。