python-mysqlHow can I use Python to perform an upsert on a MySQL database?
Upsert is a combination of update and insert operations in a database. To perform an upsert in a MySQL database with Python, we can use the MySQL Connector/Python library. The following example code will perform an upsert on a table named my_table
:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO my_table (name, address) VALUES (%s, %s) ON DUPLICATE KEY UPDATE address = %s"
val = ("John", "Highway 21", "Valley 345")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
This code will output: 1 record inserted.
The code consists of the following parts:
- Importing the MySQL Connector/Python library:
import mysql.connector
- Connecting to the database:
mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase")
- Creating a cursor object:
mycursor = mydb.cursor()
- Preparing the SQL query:
sql = "INSERT INTO my_table (name, address) VALUES (%s, %s) ON DUPLICATE KEY UPDATE address = %s"
- Executing the query:
mycursor.execute(sql, val)
- Committing the changes to the database:
mydb.commit()
- Printing the result:
print(mycursor.rowcount, "record inserted.")
For more information, please refer to the MySQL Connector/Python documentation.
More of Python Mysql
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I use Python to authenticate MySQL on Windows?
- How do I check the version of MySQL I am using with Python?
- How do I use Python to update multiple columns in a MySQL database?
- How do I connect to a MySQL database using Python and MySQL Workbench?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I decide between using Python MySQL and PyMySQL?
See more codes...