Bartek Malysz
Bartek Malysz

Reputation: 1022

How to update rows in SQL database using SQLAlchemy and pandas (simple way)

Is it possible to use df.to_sql() in a way it only replaces values available in df it's called on without scraping the whole table as it happens when you pass 'if_exists=replace'?

I've seen examples with convoluted code, sessionmakers, etc. like in the below examples:

How to update SQLAlchemy row entry?

Updating specific row in SQLAlchemy

Updating row in SqlAlchemy ORM

but it's too convoluted. Following an example on SQLAlchemy I tried:

https://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Update

from sqlalchemy.sql import update, table, column, select, text
update(table('tbl_plans')).where("portfolio_id_host=='TESTING'").values(portfolio_id_host='Tested')

but all it produces is:

<sqlalchemy.sql.dml.Update object at 0x00000193C18F8630>

and no actual update is made.

Using .to_sql() on df with only rows I want to update drops the existing table, creates new one, inserts rows. Is there an elegant / efficient way to do update just what I need? (by update I don't mean, delete, create, insert) but actual UPDATE SQL equivalent

Upvotes: 1

Views: 2679

Answers (1)

Jan
Jan

Reputation: 685

sqlalchemy.sql.update generates an object representing an update statement without executing it.

To use it, you have to run Connection.execute()

See the tutorial

Upvotes: 2

Related Questions