dedtech.info

Information about computer technology.

Delete A MySQL Database Table Row With Python

This blog post will explain how to delete a row in a MySQL database table using python.

This is what the database table will look like.

idname
1larry
2curly
3moe

The mysql.connector library has to be imported so the program can interact with a MySQL database table to delete a row.

import mysql.connector

The variable result is set to 1. It will determine which row gets deleted by the delete query.

result = 1

The connection to the database is established.

sql = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="pass",
  database = "somedatabase"
)

A cursor is created to traverse the rows of a table.

cursor = sql.cursor()

The statements below perform the delete query.

query = f"DELETE FROM names WHERE id = {result}"
cursor.execute(query)
sql.commit()

The rows in the updated table are retrieved.

query = "SELECT * FROM names"
cursor.execute(query)
rows = cursor.fetchall()

The rows are printed out.

for row in rows:
    print(row)

The cursor and database connection are terminated.

cursor.close()
sql.close()

This is what the whole source code looks like.


import mysql.connector

result = 1
 
sql = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="pass",
  database = "somedatabase"
)

cursor = sql.cursor()

query = f"DELETE FROM names WHERE id = {result}"
cursor.execute(query)
sql.commit()

query = "SELECT * FROM names"
cursor.execute(query)
rows = cursor.fetchall()

for row in rows:
    print(row)

cursor.close()
sql.close()

Leave a Reply

Your email address will not be published. Required fields are marked *