Reputation: 13
I am trying to delete multiple rows in mysql table, through a loop in python. There is no error message but finally the table is not being updated. My code is:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="Share")
mycursor = mydb.cursor()
for i in range(288, 297):
sql = "DELETE from name_list where ID = " + str(i)
mycursor.execute(sql)
mydb.commit()
mycursor.execute("SELECT * from Share.name_list")
for row in mycursor.fetchall() :
print(row)
Thanks
Upvotes: 2
Views: 1690
Reputation: 3959
How about this?
for i in range(288, 297):
sql = "DELETE from name_list where ID = %s"
mycursor.execute(sql, (i, ))
mydb.commit()
this should automatically quote the variable based on the datatype and has the added benefit of sql injection protection.
In this case it doesn't matter, since the parameter is always generated by range()
but concatenating variables into sql queries manually is generally bad habit.
Upvotes: 3