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 retrieve data from MySQL?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How can I host a MySQL database using Python?
- How do I fix a bad MySQL handshake error in Python?
- How can I connect Python to a MySQL database using an Xserver?
- 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 and MySQL?
See more codes...