蟒蛇。以徽章存储在数据库中-除非有新ID否则请更换

时间:2019-05-21 09:29:32

标签: python python-3.x sqlalchemy

我一次以X个用户的身份写入数据库,我想更新用户信息(替换行)。我只希望每个用户只有一行。

但是,当使用参数if_exists='replace'时,新徽章将替换旧徽章(删除以前的-distinct-用户)。

如果我改为使用'append',我将得到大量重复数据。

我的表有多个列作为PK,因此我使用krvkir中的以下定义:https://stackoverflow.com/a/31045044/9153261

def to_sql_k(self, frame, name, if_exists='fail', index=False, index_label=None, 
             schema=None, chunksize=None, dtype=None, **kwargs):
    '''Definition to add PK'''
    if dtype is not None:
        for col, my_type in dtype.items():
            if not isinstance(to_instance(my_type), TypeEngine):
                raise ValueError('The type of %s is not a SQLAlchemy '
                                    'type ' % col)

    table = pd.io.sql.SQLTable(name, self, frame=frame, index=index,
                        if_exists=if_exists, index_label=index_label,
                        schema=schema, dtype=dtype, **kwargs)
    table.create()
    table.insert(chunksize)

我正在使用另一个定义将信息存储到数据库中:

def writting_in_db(df, user_list, engine):
    try:    
        ddtype={
            'User': INTEGER,
            'C1': INTEGER,
            'C2': INTEGER
        }

        pandas_sql = pd.io.sql.pandasSQL_builder(engine)
        to_sql_k(pandas_sql, df, 'TableName', keys=('User', 'C1'), 
                 if_exists='append', dtype=ddtype)

    except:
        print("Exception, this list of users was not updated into database:\n")
        sys.stdout.flush()
        print(user_list)
        sys.stdout.flush()

是否有没有“在每次迭代之前删除数据库的所有内容”的解决方案?

理想情况下也不是,“查询数据库上的所有现有用户,并进行迭代以查看它们是否存在于要导出的新df中”。

沙鲁特

0 个答案:

没有答案