python-mysqlHow do I use the "on duplicate key update" statement in Python and MySQL?
The on duplicate key update
statement in Python and MySQL is used to update existing records in a table when a duplicate key is inserted. It is useful for preventing duplicate records in a database table. The syntax is as follows:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...)
ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2, column3 = value3, ...;
For example, if we have a table called students
with a primary key of student_id
and we want to update the name
and age
columns when a duplicate student_id
is inserted, we could use the following query:
INSERT INTO students (student_id, name, age)
VALUES (2, 'John', 25)
ON DUPLICATE KEY UPDATE name = 'John', age = 25;
The parts of this code are:
INSERT INTO students
- This statement is used to insert data into thestudents
table.(student_id, name, age)
- This specifies the columns that the data will be inserted into.VALUES (2, 'John', 25)
- This specifies the values to be inserted into the specified columns.ON DUPLICATE KEY UPDATE
- This statement is used to update existing records in the table when a duplicate key is inserted.name = 'John', age = 25;
- This specifies the columns and values to be updated when a duplicate key is inserted.
Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How can I connect Python to a MySQL database?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python to interact with a MySQL database using YAML?
- How do I connect Python with MySQL using XAMPP?
- How can I connect to MySQL using Python?
- How do I access MySQL using Python?
- How do Python and MySQL compare to MariaDB?
- How can I access MySQL using Python?
- How can I connect Python and MySQL?
See more codes...