首页 > 解决方案 > Python psycopg2删除具有多个where条件的记录

问题描述

我正在尝试删除具有 2 个 where 条件的 postgres 表中的记录。为此,我正在使用psycopg2. 现在每个条件的值都存储在一个列表中。

下面是代码片段:

def delete_record(tbl_name,locations,files):
    try:
        conn = psycopg2.connect('connection string')
        conn.autocommit = True
        curr = conn.cursor()
        ods_tb = pd.read_sql_query('SELECT * FROM ods.{};'.format(tbl_name),conn)
        ods_tb_row = ods_tb.shape[0]
        for l in locations:
            for f in files:
                ods_tbl_select = pd.read_sql_query("""SELECT * FROM ods.{} where location='{1}' and filename='{2}';""".format(tbl_name,l,f),conn) 
    #<-- Please check the above line##
                if ods_tbl_select:
                    for l in locations:
                        for f in files:
                            curr.execute("""DELETE  FROM ods.{} where location=%s and filename=%s;""".format(tbl_name), (l,f,) ) 
    #<-- Also please check the above line. Is this a valid way of operation on DB##                        
                            row_deleted = curr.rowcount
                            conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        msg = str(error)
    finally:
        if conn is not None:
            conn.close()
    return row_deleted,ods_tb_row,msg

在上述位置和文件如下所示:

locations = ['ABC','XYZ']
files = ['file_1.txt','file_2.txt']

客观的:

location我希望根据和中列出的条件删除数据库记录files

我的问题是:

上述方法可行吗?有更好的选择吗?

PS:到目前为止,我还没有直接在 DB 上尝试过上述方法。因为数据库正在生产中,我已经转储并想在本地数据库上尝试上述操作。

标签: pythonpostgresql

解决方案


推荐阅读