SQLAlchemy Core
In this example, we have used the SQLAlchemy Core. The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, and score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list.
By using the select() method:
Python
import sqlalchemy as db # Define the Engine (Connection Object) engine = db.create_engine("mysql + pymysql: / / \ root:password@localhost / Geeks4Geeks") # Create the Metadata Object meta_data = db.MetaData() meta_data.reflect(bind = engine) #don't follow the following syntax for creating the meta_data #meta_data=MetaData(bind=engine) #Here MetaData class doesn't have any argument bind,so we get arror. # Get the `students` table from the Metadata object STUDENTS = meta_data.tables[ 'students' ] # SQLAlchemy Query to SELECT specific column query = db.select( STUDENTS.c.first_name, STUDENTS.c.last_name ) #don't use [STUDENT.c.first_name,....] give ArgumentError #[STUDENT.c.first_name,....] the syntax in older versions only # Fetch all the records result = engine.execute(query).fetchall() # View the records for record in result: print ( "\n" , record[ 0 ], record[ 1 ]) |
Output:
Querying and selecting specific column in SQLAlchemy
In this article, we will see how to query and select specific columns using SQLAlchemy in and
For our examples, we have already created a Students table which we will be using:
Selecting specific column in SQLAlchemy:
Syntax: sqlalchemy.select(*entities)
Where: Entities to SELECT from. This is typically a series of ColumnElement for Core usage and ORM-mapped classes for ORM usage.