Extract complete rows in SQLAlchemy
Selecting rows in a table has a slightly different procedure than that of a conventional SQL query which is shown below
sqlalchemy.select(Tablename).whereTablename.c.column_name == condition)
Get the books table from the Metadata object initialized while connecting to the database. Pass the SQL query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results. The SQLAlchemy query shown in the below code selects all rows where the row contains a “fiction” genre.
Python3
# Get the books table from the Metadata object BOOKS = meta.tables[ 'books' ] # SQLAlchemy Query to select all rows with # fiction genre query = sqlalchemy.select(BOOKS).where(BOOKS.c.genre = = 'fiction' ) # Fetch all the records result = engine.execute(query).fetchall() # View the records for record in result: print ( "\n" , record) |
Output:
SQLAlchemy Core – Selecting Rows
In this article, we are going to see how to write a query to get all rows based on certain conditions in SQLAlchemy against a PostgreSQL database in python.