python-mysqlHow do I use Python to update multiple columns in a MySQL database?
You can use Python to update multiple columns in a MySQL database by using the UPDATE
command. For example, the following code will update the name
and age
columns of the users
table:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE users SET name = 'John', age = '32' WHERE name = 'Peter'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
Output example
1 record(s) affected
Explanation of the code:
import mysql.connector
: This imports the MySQL Connector Python module in order to establish a connection to the database.mydb = mysql.connector.connect()
: This establishes a connection to the database using the credentials provided as parameters.mycursor = mydb.cursor()
: This creates a cursor object which is used to execute the SQL statements.sql = "UPDATE users SET name = 'John', age = '32' WHERE name = 'Peter'"
: This is the SQL statement used to update thename
andage
columns of theusers
table.mycursor.execute(sql)
: This executes the SQL statement.mydb.commit()
: This commits the changes to the database.print(mycursor.rowcount, "record(s) affected")
: This prints the number of records affected by the query.
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a SELECT statement in Python to query a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I insert JSON data into a MySQL database using Python?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I use Python to show the MySQL processlist?
See more codes...