插入 oracle 时,如果某个列存在唯一约束,同时批量插入时数据重复,会报 error,此时将 error 的过滤掉,最后 commit

def insert_one_by_one():
    from sqlalchemy import create_engine
    engine = create_engine("oracle://user:pass@xx.xx.xx.xx:xxxx/?service_name=xxx.xxx.xxx", echo=True)
 
    user_list = [{'username': 'jalen1', 'age': '11', 'height': '123'},
                 {'username': 'jalen2', 'age': '12', 'height': '124'},
                 {'username': 'jalen3', 'age': '13', 'height': '125'},
                 {'username': 'jalen4', 'age': '14', 'height': None}]
 
    conn = engine.connect()
    trans = conn.begin()
    try:
        for user in user_list:
            try:
                sql = "INSERT INTO tb_user(username, age, height) VALUES('{0}', '{1}', '{2}')".\
                    format(user['username'], user['age'], user['height'])
                conn.execute(sql)
            except Exception as e:
                logger.info(e.message)
        trans.commit()
    except Exception:
        trans.rollback()
        raise
    finally:
        conn.close()