I'm working with the SQLAlchemy Expression Language (not the ORM), and I'm trying to figure out how to update a query result.
I've discovered that RowProxy objects don't support assignment, throwing an AttributeError
instead:
# Get a row from the table
row = engine.execute(mytable.select().limit(1)).fetchone()
# Check that `foo` exists on the row
assert row.foo is None
# Try to update `foo`
row.foo = "bar"
AttributeError: 'RowProxy' object has no attribute 'foo'
I've found this solution, which makes use of the ORM, but I'm specifically looking to use the Expression Language.
I've also found this solution, which converts the row to a dict and updates the dict, but that seems like a hacky workaround.
So I have a few questions:
A ResultProxy is a wrapper around a DBAPI cursor object, and its main goal is to make it easier to use and manipulate the results of a statement. Simple select example: from sqlalchemy.sql import select stmnt = select([cookies]) result_proxy = connection.execute(stmnt) results = result_proxy.fetchall()
Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.
You are misusing SQLAlchemy. The usage you've described is the benefit of using an ORM. If you only want to restrict yourself to SQLAlchemy Core, then you need to do
engine.execute(mytable.update().where(mytable.c.id == <id>).values(foo="bar"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With