Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python mysql – can not delete row from database

I am trying to delete a row from my database but nothing worked. here is my code:

import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="user",passwd="1",database="workers")
mycursor = mydb.cursor()
query = "DELETE FROM `workers` WHERE id = %s"
# connect to the database server
# execute the query
mycursor.execute(query, (1,)) 
mysql.commit()  # You need to commit the transaction

Note: I am using python3.10, and my operating system is ubuntu. I also try to use %d instead of %s, but it does not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I created a test table:

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.2.0     |
+-----------+

mysql> create table workers (id serial primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into workers values (1), (2);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from workers;
+----+
| id |
+----+
|  1 |
|  2 |
+----+

Demo script delete-test.py:

import mysql.connector

if __name__ == '__main__':
    config = { ... }

    mydb = mysql.connector.connect(**config)
    mycursor = mydb.cursor()

    # FIXED: use %s instead of %d
    query = "DELETE FROM `workers` WHERE id = %s"

    mycursor.execute(query, (1,))

    # FIXED: mydb instead of mysql 
    mydb.commit()

    mycursor.close()
    mydb.close()

Run script:

% python3 --version
Python 3.11.4
% python3 ./delete-test.py
%

Check results:

mysql> select * from workers;
+----+
| id |
+----+
|  2 |
+----+
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading