问题
I'm trying to write a valid mysql statement that would allow me to update multiple columns in one record with values provided as python variables.
My statement would look like this:
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()
While trying to execute the query, I keep receiving information that there is an error in my SQL syntax. I can't locate it though. Could someone point out my mistake or show me how it should be written?
回答1:
You are using string formatting, while what you SHOULD be doing is using a parametrized query. Do it like this:
cursor.execute("UPDATE table_name SET field1=%s ... field10=%s WHERE id=%s", (var1,... var10, id))
Did you really need to post it with 10 variables? It was so frustrating to format, I gave up.
回答2:
I did it as:
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
has all parameters to replace in sql
command. The value of lstNuevosVal
is
['Soporte 1', '6.35', '7.36', '8.37', '9.38', '10.39', 'Soporte 306048\nCabeza 3072589\nMáquina: Deco20\n\n']
回答3:
Maybe it's about apostrophes around string/VARCHAR values:
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)
来源:https://stackoverflow.com/questions/1081750/python-update-multiple-columns-with-python-variables