Pixel
Pixel

Reputation: 910

Avoid Duplicate entry error

I'm using MySQLdbto insert records in my database, I created a table with an UNIQUE KEY on the domain field.

I would like to avoid the error : IntegrityError: (1062, "Duplicate entry 'xxxxx.com' for key 'domain'").

How can I do that ?

My code is here :

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()

Upvotes: 1

Views: 742

Answers (1)

e4c5
e4c5

Reputation: 53744

Try using INSERT ... ON DUPLCATE KEY UPDATE

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

Upvotes: 2

Related Questions