Karan Jain
Karan Jain

Reputation: 415

Parameterize the delete function sqlalchemy

I have a function to delete a row from psql database

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()

I can parameterize the table name but I also want to parameterize the key-value pair to be searched for and then deleted. In the above example country_table.c.id where id is the column in the table, but i want to generalize the column name

Upvotes: 0

Views: 92

Answers (1)

M Dennis
M Dennis

Reputation: 177

Because of Table.c is a collection it should be:

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()

See here

Upvotes: 1

Related Questions