python - 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 上尝试过上述方法。因为数据库正在生产中,我已经转储并想在本地数据库上尝试上述操作。
解决方案
推荐阅读
- android - beeware将toga imageview添加到android
- c++ - 队列和文本文件
- amazon-web-services - AWS Data Exchange 限制如何避免?
- angular - NgRx 存储选择器单元测试
- java - 如何使用以当前日期为输入的java获取下一个日期
- c# - Xna 可破坏的墙壁
- microsoft-graph-api - 尝试在 MS Graph 中创建会议时出现内部服务器错误
- linux - ln:创建符号链接失败:文件存在
- angularjs - 如何设置织物组的边界框旋转和尺寸与其对象相同
- c - 在C中找到数组中的最小数字的问题