2017-04-19 82 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方法返回行列表一样。