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 use Python to interact with a MySQL database using YAML?
- How can I use the MySQL Connector in Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to show the MySQL processlist?
- How can I use Python and MySQL to generate a PDF?
- How can I compare and contrast using Python with MySQL versus PostgreSQL?
- How can I connect to a MySQL database using Python and SSH?
- How can I use Python to update multiple rows in a MySQL database?
- How do I write a Python MySQL query?
See more codes...