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) updatedThe code above consists of the following parts:
- Import the MySQL Connector/Pythonlibrary
- Establish a connection to the MySQL database
- Create a cursor object
- Construct an UPDATEstatement
- 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 and MySQL to generate a PDF?
- How can I connect Python and MySQL?
- How do I create a Python script to back up my MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect to MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I use Python to query MySQL with multiple conditions?
See more codes...