如何在Python的 SQLAlchemy 中使用 IN运算符?
在本文中,我们将了解如何在Python中使用 SQLAlchemy 使用 IN运算符。
我们将介绍 2 个示例,每个示例用于 SQLAchemy Core 和 ORM 层。在这两个示例中,我们将计算sakila数据库中类别表中存在的记录数。表中的示例数据如下所示。
如果您没有sakila数据库并且想在不安装它的情况下跟随本文,那么使用下面的 SQL 脚本来创建所需的模式和类别表以及记录。
CREATE DATABASE IF NOT EXISTS `sakila`;
USE `sakila`;
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`category_id` tinyint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`category_id`)
);
INSERT INTO `category`
VALUES
(1, 'Action', '2006-02-14 23:16:27'),
(2, 'Animation', '2006-02-14 23:16:27'),
(3, 'Children', '2006-02-14 23:16:27'),
(4, 'Classics', '2006-02-14 23:16:27'),
(5, 'Comedy', '2006-02-14 23:16:27'),
(6, 'Documentary', '2006-02-14 23:16:27'),
(7, 'Drama', '2006-02-14 23:16:27'),
(8, 'Family', '2006-02-14 23:16:27'),
(9, 'Foreign', '2006-02-14 23:16:27'),
(10, 'Games', '2006-02-14 23:16:27'),
(11, 'Horror', '2006-02-14 23:16:27'),
(12, 'Music', '2006-02-14 23:16:27'),
(13, 'New', '2006-02-14 23:16:27'),
(14, 'Sci-Fi', '2006-02-14 23:16:27'),
(15, 'Sports', '2006-02-14 23:16:27'),
(16, 'Travel', '2006-02-14 23:16:27');
我们在以下两个示例中查看的 SQL 查询是:
SELECT category_id, name FROM category WHERE name IN (“Action”, “Horror”, “Sci-Fi”);
SQLAlchemy 核心
在上面的示例中,参考之前创建的类别表,我们过滤掉了名称字段中包含“动作”、“恐怖”或“科幻”之一的记录。我们从类别表中选择 category_id 和 name 列。如我们所见,该示例对应于 SQLAlchemy Core,我们使用元数据对象来获取有关表的元数据信息。现在,让我们看看如何使用 SQLAlchemy ORM 做同样的事情。
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `category` TABLE FROM THE METADATA OBJECT
category_table = meta_data.tables['category']
# SELECT category_id, name FROM category
# WHERE name IN ("Action", "Horror", "Sci-Fi");
query = db.select([
category_table.c.category_id,
category_table.c.name
]).where(
category_table.c.name.in_([
"Action", "Horror", "Sci-Fi"
])
)
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).fetchall()
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print("\n", record)
Python
# IMPORT REQUIRED LIBRARIES
from sqlalchemy.orm import sessionmaker
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/sakila")
# CREATE THE TABLE MODEL TO USE IT FOR QUERYING
class Category(Base):
__tablename__ = 'category'
category_id = db.Column(
db.SmallInteger, primary_key=True,
autoincrement=True)
name = db.Column(db.String(25))
last_update = db.Column(db.DateTime)
# CREATE A SESSION OBJECT TO INITIATE QUERY IN DATABASE
Session = sessionmaker(bind=engine)
session = Session()
# SELECT category_id, name FROM
# category WHERE name IN
# ("Action", "Horror", "Sci-Fi");
result = session.query(Category.category_id, Category.name) \
.filter(
Category.name.in_(("Action", "Horror", "Sci-Fi"))
)
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print("\n", record.category_id, "-", record.name)
输出:
SQLAchemy ORM
ORM 示例结果与 Core 示例获得的结果相同。两者的区别在于语法。对于 ORM,我们需要定义表模型。在上面的代码中,我们创建了 Category 类,它还定义了表中存在的不同字段或列。我们使用这个类来查询数据库。由于使用了类模型,ORM 在 SQLAlchemy 中感觉更加 Pythonic。但是,当您的程序应该定义数据库模式和架构时,它是首选,否则 Core 可以证明非常方便。
Python
# IMPORT REQUIRED LIBRARIES
from sqlalchemy.orm import sessionmaker
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/sakila")
# CREATE THE TABLE MODEL TO USE IT FOR QUERYING
class Category(Base):
__tablename__ = 'category'
category_id = db.Column(
db.SmallInteger, primary_key=True,
autoincrement=True)
name = db.Column(db.String(25))
last_update = db.Column(db.DateTime)
# CREATE A SESSION OBJECT TO INITIATE QUERY IN DATABASE
Session = sessionmaker(bind=engine)
session = Session()
# SELECT category_id, name FROM
# category WHERE name IN
# ("Action", "Horror", "Sci-Fi");
result = session.query(Category.category_id, Category.name) \
.filter(
Category.name.in_(("Action", "Horror", "Sci-Fi"))
)
# VIEW THE ENTRIES IN THE RESULT
for record in result:
print("\n", record.category_id, "-", record.name)
输出: