python-mysqlHow do I update values in a MySQL database using Python?
Updating values in a MySQL database using Python is a relatively straightforward process. The following example code shows how to update a value in a MySQL database using Python:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
Output example
1 record(s) affected
The code above consists of the following parts:
- Importing the mysql.connector module.
- Connecting to the database using the mysql.connector.connect() function.
- Creating a cursor object using the mydb.cursor() method.
- Creating an SQL query to update the value in the database.
- Executing the query using the mycursor.execute() method.
- Committing the changes to the database using the mydb.commit() method.
- Printing the number of records affected with the mycursor.rowcount property.
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python and MySQL?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a cursor to interact with a MySQL database in Python?
- How can I host a MySQL database using Python?
See more codes...