【问题标题】:PYTHON: Update MULTIPLE COLUMNS with python variablesPYTHON:使用 python 变量更新多列
【发布时间】:2009-07-04 07:42:43
【问题描述】:

我正在尝试编写一个有效的 mysql 语句,它允许我使用作为 python 变量提供的值更新一条记录中的多个列。

我的陈述应该是这样的:

db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
cursor = db.cursor()
sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
cursor.execute(sql_update)
cursor.close ()
db.commit()
db.close()

在尝试执行查询时,我不断收到有关我的 SQL 语法有错误的信息。我找不到它。 有人能指出我的错误或告诉我应该怎么写吗?

【问题讨论】:

    标签: python mysql variables


    【解决方案1】:

    您正在使用字符串格式,而您应该做的是使用参数化查询。这样做:

    cursor.execute("UPDATE table_name SET field1=%s, ..., field10=%s WHERE id=%s", (var1,... var10, id))
    

    【讨论】:

    • 如果有人仍然有问题,我遵循了这种格式,但它不起作用。在多个字段之间使用逗号,然后它就起作用了。 like => SET field1=%s, field2=%s, field3=%s WHERE criteria1=%s
    【解决方案2】:

    请考虑以下注意事项:

    • 您应该确保用户名和密码正确
    • 占位符的数量必须与值的数量相匹配
    • 您使用的值类型与表中列的类型相匹配

    请尝试以下代码:

    db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
    cursor = db.cursor()
    sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s"
    val =  (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
    cursor.execute(sql_update, val)
    db.commit()
    cursor.close ()
    db.close()
    

    【讨论】:

      【解决方案3】:

      我是这样做的:

          def bscaSoporte(self, denom_sop):
              soporte = (denom_sop,) #Para que tome la variable, lista
              sql= 'SELECT * FROM SOPORTE_ID WHERE denom_sop LIKE ?'
              self.cursor1.execute(sql, soporte)
              return self.cursor1.fetchall()
      
          def updSoporte(self, lstNuevosVal):
              #busca soporte, SOLO HAY UNO que cumpla
              denom_sop = lstNuevosVal.pop(0)
              print(lstNuevosVal)
              encontrado = self.bscaSoporte(denom_sop)
              soporte = (denom_sop,) #Para que tome la variable, lista
              if encontrado != None:
                  sqlupdate =('UPDATE SOPORTE_ID SET  dst_pln_eje = ?, geom_Z_eje = ?, \
                  geom_Y_0_grd = ?, dst_hta_eje = ?,  geom_Z_0_grd = ?, \
                  descrip = ? WHERE denom_sop  LIKE ?')
              #añado denom_soporte al final de la lista
              lstNuevosVal.append(denom_sop)
              self.cursor1.execute(sqlupdate, (lstNuevosVal))
              self.conexion.commit() 
      

      lstNuevosVal 具有要在sql 命令中替换的所有参数。 lstNuevosVal 的值为

      ['Soporte 1', '6.35', '7.36', '8.37', '9.38', '10.39', 'Soporte 306048\nCabeza 3072589\nMáquina: Deco20\n\n']
      

      【讨论】:

        【解决方案4】:
        def UpdateData(lVideoList, no_of_gate):
            connection = sqlite3.connect('db.sqlite',
                                         detect_types=sqlite3.PARSE_DECLTYPES |
                                                      sqlite3.PARSE_COLNAMES)
            cursor = connection.cursor()
            success = 200
            unsuccess = 500
            default_value = 0
            for i in range(no_of_gate):
                gate_id = i+1
                for videofilename in lVideoList:
        ##            print("videofilename: ", videofilename)
                    ldate = videofilename[0:10]
                    sql_select_Query = "select * from dailyfootfall where csv_name LIKE '"+ldate+"%'"
                    cursor.execute(sql_select_Query)
        
                    result  = cursor.fetchall()
                    print(result)
        
                    if len(result)>0 :
                        try:
                            
                            print ('Entry Not found...!!!')
                            insert_query = ("INSERT or IGNORE INTO dailyfootfall(csv_name, video_download, processed, footfall, send_status, "
                                            "male_footfall, send_status_male, female_footfall, send_status_female, gate_id,outsiders, send_status_outsiders) "
                                            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)")
        
                            cursor.execute(insert_query,[videofilename, unsuccess, unsuccess, default_value, unsuccess, default_value,
                                                         unsuccess, default_value, unsuccess, gate_id, default_value, unsuccess])
        
                            print("Data_Inserted..!!")
                            print("="*20)
                        except Exception as e:
                            
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                            print("entry Not found"exc_type, fname, exc_tb.tb_lineno)
                            
                    else:
                        try:
                            
                            print ('Entry found...!!!')
        
                            cursor.execute("UPDATE dailyfootfall SET video_download=?, processed=?, footfall=?, send_status=? ,male_footfall=?, send_status_male=?, "
                                           "female_footfall =?,send_status_female=?, outsiders=?, send_status_outsiders=? "
                                           "WHERE csv_name=? AND gate_id=?", [unsuccess,unsuccess,default_value,unsuccess,default_value,unsuccess,default_value,
                                                                              unsuccess,default_value,unsuccess,videofilename,gate_id])
                            print("Data_Updated..!!!")
        
                            
                        except Exception as e:
                            exc_type, exc_obj, exc_tb = sys.exc_info()
                            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                            print("Entry found: "exc_type, fname, exc_tb.tb_lineno)
        
               
            print("Data Inserted Successfully !")
            connection.commit()
            cursor.close()
            connection.close()
        

        【讨论】:

        • 您好,感谢您的回答。如果您添加了关于您的代码的作用以及它为何对 OP 有帮助的解释,您的回答对我们来说会更有价值
        【解决方案5】:

        也许是关于字符串/VARCHAR 值周围的撇号:

        sql_update = "UPDATE table_name SET field1='%s', field2='%s', field3='%s', field4='%s', field5='%s', field6='%s', field7='%s', field8='%s', field9='%s', field10='%s' WHERE id='%s'" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-09
          • 2018-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多