Avoid Duplicate entry error
<p>I'm using <code>MySQLdb</code>to insert records in my database, I created a table with an <code>UNIQUE KEY</code> on the <code>domain field</code>.<br></p>

<p>I would like to avoid the error : <code>IntegrityError: (1062, "Duplicate entry 'xxxxx.com' for key 'domain'")</code>.<br></p>

<p>How can I do that ?</p>

<p><strong>My code is here :</strong></p>

<pre><code>try:
    CONN = MySQLdb.connect(host=SQL_HOST,
                           user=SQL_USER,
                           passwd=SQL_PASSWD,
                           db=SQL_DB)
except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit(1)

cursor = CONN.cursor()

def insert_table(domain, trust_flow, citation_flow, ref_domains, ext_back_links):
    sql = "INSERT INTO %s (domain, TrustFlow, CitationFlow, RefDomains, ExtBackLinks) values('%s','%s','%s','%s','%s')" % (SQL_TABLE, domain, trust_flow, citation_flow, ref_domains, ext_back_links)
    if cursor.execute(sql):
        CONN.commit()
</code></pre>

<p>Try using <a href="http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html" rel="nofollow">INSERT ... ON DUPLCATE KEY UPDATE</a></p>

<pre><code>INSERT INTO %s (domain, TrustFlow, CitationFlow, RefDomains, ExtBackLinks) values('%s','%s','%s','%s','%s') 
ON DUPLICATE KEY UPDATE TrustFlow = VALUES(TrustFlow), CitationFlow = VALUES(CitationFlow) ....
</code></pre>

python mysql python-2.7 scrapy