Python & MySQL - Update Records Example



Python uses c.execute(q) function to update a record from a table where c is cursor and q is the update 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 update record(s) in a table.

Example

Try the following example to update records in a table −

Copy and paste the following example as mysql_example.ty −

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")

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

sql = "UPDATE tutorials_tbl set tutorial_title = "Learning Java" 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 mysql_example.py script using python and verify the output.

1 record(s) affected
Advertisements