在 SQLAlchemy 中查询和选择特定列
在本文中,我们将了解如何在Python中使用 SQLAlchemy 查询和选择特定列。
对于我们的示例,我们已经创建了一个学生表,我们将使用它:
在 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.
SQLAlchemy 核心
在这个例子中,我们使用了 SQLAlchemy Core。引用了已经创建的学生表,其中包含 4 列,即first_name 、 last_name 、 course 、 score 。但是我们只会选择一个特定的列。在示例中,我们引用了first_name和last_name列。实体列表中也可以提供其他列。
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(bind=engine)
db.MetaData.reflect(meta_data)
# 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
])
# Fetch all the records
result = engine.execute(query).fetchall()
# View the records
for record in result:
print("\n", record[0], record[1])
Python
import sqlalchemy as db
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# DEFINE THE ENGINE (CONNECTIO OBJECT)
engine = db.create_engine("mysql+pymysql:/\
/root:password@localhost/Geeks4Geeks")
# CREATE THE TABLE MODEL TO USE IT FOR QUERYING
class Students(Base):
__tablename__ = 'students'
first_name = db.Column(db.String(50),
primary_key=True)
last_name = db.Column(db.String(50),
primary_key=True)
course = db.Column(db.String(50))
score = db.Column(db.Float)
# SQLAlCHEMY CORE QUERY TO FETCH SPECIFIC COLUMNS
query = db.select([Students.first_name, Students.last_name])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).fetchall()
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print(record[0], record[1])
输出:
SQLAlchemy ORM
在这个例子中,除了它是基于 SQLAlchemy ORM 构建的之外,它与上一个例子类似。 SQLAlchemy ORM 是 SQLAlchemy 的一个更加 Python 的实现,正如您在代码中看到的,我们创建了一个Python类来引用学生表。两种情况下的语法都是相同的,只是我们定义列名的方式略有不同。 ORM 中的列是使用 ORM 映射的类定义的。两者的输出相同,因为我们在此示例中也采用了first_name和last_name列。
Python
import sqlalchemy as db
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# DEFINE THE ENGINE (CONNECTIO OBJECT)
engine = db.create_engine("mysql+pymysql:/\
/root:password@localhost/Geeks4Geeks")
# CREATE THE TABLE MODEL TO USE IT FOR QUERYING
class Students(Base):
__tablename__ = 'students'
first_name = db.Column(db.String(50),
primary_key=True)
last_name = db.Column(db.String(50),
primary_key=True)
course = db.Column(db.String(50))
score = db.Column(db.Float)
# SQLAlCHEMY CORE QUERY TO FETCH SPECIFIC COLUMNS
query = db.select([Students.first_name, Students.last_name])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).fetchall()
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print(record[0], record[1])
输出: