Python MySql - Deleting Records from a Table



Python uses c.execute(q) function to delete a record from a table where c is cursor and q is the delete query to be executed.

Syntax

# execute SQL query using execute() method.
cursor.execute(sql)

cursor.commit()

# get the record count updated
print(mycursor.rowcount, "record(s) affected")
Sr.No. Parameter & Description
1

$sql

Required - SQL query to delete record(s) in a table.

Example - Inserting Records in a Table

Try the following example to insert records in a table −

Copy and paste the following example as main.py −

main.py

import mysql.connector

# Open database connection
db = mysql.connector.connect(host="localhost",user="root",password="root@123", database="TUTORIALS")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "Delete from tutorials_tbl where tutorial_id = 2"

# execute SQL query using execute() method.
cursor.execute(sql)

db.commit()

# get the record count updated
print(cursor.rowcount, " record(s) affected")

# disconnect from server
db.close()

Output

Execute the main.py script using python and verify the output.

1 record(s) affected
Advertisements