Python psycopg2删除具有多个where条件的记录

时间:2019-09-23 07:34:06

标签: python postgresql

我正在尝试删除条件为2的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']

目标:

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

我的问题是:

以上方法行得通吗?有更好的选择吗?

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

0 个答案:

没有答案