我正在使用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()

最佳答案

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

关于python - 避免重复输入错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39850379/

10-12 23:49