How to avoid duplicate records in MySQL database without throwing an error

I am using Python-MySQL library (MySQLdb) to insert values ​​into a database. I want to avoid duplicate records from the database, so I added a constraint unique

to this column in MySQL. I am checking for duplicates in a column title

. In my Python script, I am using the following statement:

cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))

      

Now, when a duplicate record is added to the database, it throws an error. I don't want the error message to appear; I just want that if a duplicate record is found, it just shouldn't enter that value into the database. How to do it?

+3


source to share


2 answers


You can use syntax INSERT IGNORE

to suppress this type of error.

If you use the IGNORE keyword, errors that occur when executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE or PRIMARY KEY index on a table raises a duplicate key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors can generate warnings instead, although there are no duplicate-key errors.



In your case, the request will look like this:

INSERT IGNORE INTO `database` (title, introduction) VALUES (%s, %s)

      

+7


source


Apart from what @Andy suggested (which should really be posted as an answer), you can also catch the exception in Python and disable it:



try:
    cursor.execute ("""INSERT INTO `database` (title, introduction) VALUES (%s, %s)""", (title, pure_introduction))
except MySQLdb.IntegrityError:
    pass  # or may be at least log?

      

+5


source







All Articles