Aarav Hari
Aarav Hari

Reputation: 13

mysql table is not committed by commit() after delete row

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

Answers (1)

redacted
redacted

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()

source

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

Related Questions