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 to a MySQL database over SSH using Python?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python and MySQL?
- How do I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I use a cursor to interact with a MySQL database in Python?
- How do Python and MySQL compare to MariaDB?
- How can I keep a MySQL connection alive in Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
See more codes...