Search code examples
pythonmysqlpython-3.xflaskdelete-row

why delete in SQL query in PYTHON doesn't commit changes in database?


DELETE FROM ... doesn't work. The right parameters are passed to the function. No errors are returned.

I've tried to modify routing, passing parameters by POST and GET, and I've cried a lot in a fetal position.

conn = mysql.connect()
cursor = mysql.connect().cursor()
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id) 
food_on_the_table = cursor.fetchall()
records = cursor.fetchall() 
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)   
conn.commit()
result = cursor.rowcount
message = "rows affected " + str(result)    
cursor.close()

No row is deleted from the database. row_i is right, rows affected = 1 as expected.


Solution

  • Try this,

    try:
        conn = mysql.connect()
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
            food_on_the_table = cursor.fetchall()
            records = food_on_the_table 
        with conn.cursor() as cursor:
            cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
    
        conn.commit()
    
    finally:
        conn.close()