【发布时间】:2020-02-04 02:44:00
【问题描述】:
我想将 SQL Server 表的行与 Pandas DataFrame 的行进行比较。我只比较某些列(构成表主键的列)。因此我不知道要提前比较多少列。我想修改以下内容以处理复合主键(作为字符串列表输入。)目前这只能处理比较一列,如果事先知道它们可以修改为处理多个但我希望它能够动态工作.
# Build the WHERE clause of your DELETE statement from rows in the dataframe.
cond = df_update_partial.apply(lambda row: sa.and_(detail_table.c[key_col] == row[key_col]), axis=1)
# trying to fix the above, right now it is set up to handle a single string column name
cond = sa.or_(*cond)
# Define and execute the DELETE
delete = detail_table.delete().where(cond)
with engine.connect() as conn:
conn.execute(delete)
因此,上面有问题的行可能需要如下所示:
cond = df_update_partial.apply(lambda row: sa.and_(detail_table.c[key_col[0]] == row[key_col[0]], detail_table.c[key_col[1]] == row[key_col[1]], detail_table.c[key_col[2]] == row[key_col[2]]), axis=1)
# above is for a primary key made up of 3 columns. key_col is a list of these columns names.
但是如果我事先不知道这个列表的长度,我就不能这样设置。
最初找到的代码here。
【问题讨论】:
标签: python sqlalchemy