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 the MySQL Connector in Python?
- How can I connect Python to a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use Python to update multiple columns in a MySQL database?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Yum to install the MySQLdb Python module?
- How can I use Python to retrieve data from MySQL?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I use Python to make a MySQL request?
See more codes...