首页 > 解决方案 > 当数据库中存在行时抛出异常

问题描述

我想在数据库 df 中插入所有数据框。如果有重复的行。我想在另一个日志表中插入这一行的一些元素。请问有谁知道该怎么做?我试过下面的代码:我没有成功捕捉到错误

#When i created my database df i put an UNIQUE key(element1, element2) So in my dataframe if i have two rows where (element1 in row i = element1 row i+1) and (element2 in row i = element2 row i+1) it is considered as duplicated.
try:
    df.to_sql(con=cnx, name='df', if_exists='append', index=False)
except mysql.connector.Error as err:
    logs = [df[0], df[1], 'INSERT', 'FAIl', str(err)]
    cursor.execute(
        "INSERT IGNORE INTO logtable (id, element, action, message) VALUES (%s, %s, %s, %s)",
        (logs))

标签: pythonmysqlpandastry-catch

解决方案


推荐阅读