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 do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I use Yum to install the MySQLdb Python module?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to show the MySQL processlist?
- How can I use Python to retrieve data from MySQL?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to connect to a MySQL database using XAMPP?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
See more codes...