2016-10-04 116 views
0

我使用MySQLdb在我的數據庫中插入記錄,我在domain field上創建了一個UNIQUE KEY表。我想避免錯誤: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

停止插入具有相同值的現有記錄的記錄。 –

回答

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