我使用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()
答案 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) ....