Google News
logo
Python Program to Update existing records in a table
To update existing records in a MySQL table using Python, you can use the following program :
Program :
import mysql.connector

# Establishing connection to the database
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# Creating a cursor object
mycursor = mydb.cursor()

# SQL statement to update records in the table
sql = "UPDATE yourtable SET column1 = 'newvalue' WHERE id = 1"

# Executing the SQL command
mycursor.execute(sql)

# Commit the changes to the database
mydb.commit()

# Closing the database connection
mydb.close()

print(mycursor.rowcount, "record(s) updated successfully!")
Note : Replace `yourusername`, `yourpassword`, `yourdatabase`, `yourtable`, `column1`, `newvalue`, and `id` with your own values.

This program updates the value of `column1` to `newvalue` where the `id` is 1 in the `yourtable` table.

The `rowcount` attribute of the cursor object returns the number of records updated.