我有一个从psql数据库中删除行的功能
def delete_from_database():
engine = connect_to_database()
# define meta information
metadata = MetaData(bind=engine)
session = sessionmaker(bind=engine)()
country_table = Table('countries', metadata, autoload=True)
# delete
delete_country_query = country_table.delete(country_table.c.id == 14)
session.execute(delete_country_query)
session.commit()
我可以参数化表名,但我也想参数化要搜索的键值对然后删除。
在上面的示例中country_table.c.id
其中id是表中的列,但我想概括列名
答案 0 :(得分:1)
由于Table.c是一个集合,它应该是:
def delete_from_database(table_name, column_name, value):
engine = connect_to_database()
# define meta information
metadata = MetaData(bind=engine)
session = sessionmaker(bind=engine)()
country_table = Table(table_name, metadata, autoload=True)
# delete
delete_country_query = country_table.delete(country_table.c[column_name] == value)
session.execute(delete_country_query)
session.commit()
请参阅here