Menu Close

Python MySQL UPDATE Statement

Python MySQL Update Statement

In this Python MySQL UPDATE tutorial, we are going to learn how to update the existing records in the MySQL database table using Python MySQL Connector.
In the previous tutorial, we have seen a complete process to drop the MySQL database table.

Make sure you have already installed MySQL connector in your machine using pip as well as create database and table.

Python MySQL Update

Python MySQL UPDATE statement to update the existing records from the database table.

Example:

In this example, we will update name of the student whose id is 5.


import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database = "demodb",
    port = 3308
	
)
cursor = mydb.cursor()
cursor.execute('UPDATE students SET name = "Aysha" WHERE id = 5')
mydb.commit()
print(cursor.rowcount, "record updated successfully.....")

Output will be:- 1 record updated successfully..

Update Multiple Records:

Here we will update age of the students whose name start with “A“.


import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="root",
	password="root21",
	database = "demodb",
    port = 3308
	
)
cursor = mydb.cursor()
cursor.execute('UPDATE students SET age = 40 WHERE name like "A%"')
mydb.commit()
print(cursor.rowcount, "records updated successfully.....")

Output will be:- 3 records updated successfully..

Note:- As you can notice in above expamles, we have used MySQL where clause to update the specific records. If you omit the use of WHERE Clause, Then it will update the whole records of table.

Python Tutorials

Conclusion

In this Python MySQL UPDATE tutorial, you have learned all about how to update existing records of MySQL database table by using an UPDATE statement.
Python MySQL connector is the best for connecting Python applications to the MySQL database and executes SQL queries. After created of database successfully, you can perform a query on that particular database.

If this article for you, please share and keep visiting for further Python MySQL database tutorials.

Python Tutorials


Python MySQL Delete
Python MySQL Create Database

Related Posts