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 to MySQL using Python?
- How can I access MySQL using Python?
- How can I connect Python and MySQL?
- How can I use Python and MySQL to create a login system?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How do I use a cursor to interact with a MySQL database in Python?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How do I connect to XAMPP MySQL using Python?
See more codes...