0

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

1
  • Please provide an example Commented Aug 9, 2017 at 12:32

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.