python-mysqlHow do I update a MySQL database using Python?
To update a MySQL database using Python, you can use the MySQL Connector/Python
library. This library provides an easy way to access and manipulate MySQL databases. Here is an example of how to update a record in a MySQL database using Python:
# Import the MySQL Connector/Python library
import mysql.connector
# Establish a connection to the MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Construct an UPDATE statement
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
# Execute the statement
mycursor.execute(sql)
# Commit the changes to the database
mydb.commit()
# Print number of rows updated
print(mycursor.rowcount, "record(s) updated")
Output example
1 record(s) updated
The code above consists of the following parts:
- Import the
MySQL Connector/Python
library - Establish a connection to the MySQL database
- Create a cursor object
- Construct an
UPDATE
statement - Execute the statement
- Commit the changes to the database
- Print number of rows updated
For more information, refer to the MySQL Connector/Python Documentation.
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I connect Python and MySQL?
- How can I use Python to make a MySQL request?
- How do I connect Python with MySQL using XAMPP?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I use Python Kivy with MySQL?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Python and MySQL to generate a PDF?
- How can I use Python to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
See more codes...