避免重复输入错误

时间:2016-10-04 10:51:56

标签: python mysql python-2.7 scrapy

我使用MySQLdb在我的数据库中插入记录,我在UNIQUE KEY上创建了一个domain field的表格。

我想避免错误:IntegrityError: (1062, "Duplicate entry 'xxxxx.com' for key 'domain'")

我该怎么做?

我的代码在这里:

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

1 个答案:

答案 0 :(得分:2)

尝试使用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) ....