ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SQLAlchemy 表达式语言 - 恰到好处

2022-11-08 15:47:16  阅读:338  来源: 互联网

标签:SQL 语言 sqlalchemy 函数 语句 DQL 操作


使用 SQLAlchemy 表达式语言进行选择

从数据库中选择属于数据库查询语言 (DQL),我们可以选择所有可用的列或从表中选择几个列。

为此,SQLAlchemy 提供了一个可以从模块导入的函数。如果兴趣仅在表列的子集中,则函数要求在函数调用中将这些列显式指定为参数。selectsqlalchemy.sqlselect

为了访问表的列,实例具有 aattribute,它是表中所有列的集合。例如返回所有列的集合 intable 和访问特定的列可以使用。sqlalchemy.Table.cItem.cItemItem.c.column_name

select_statement = select(Item.c.name, Item.c.id, Item.c.category, ...)

要检索所有列,可以显式指定每个列(如上面的代码片段),也可以按原样给出表实例。

select_statement = select(Item)

db/scripts/items_el.py

class DQL:
    """Encapsulates database query language (DML)"""

    @staticmethod
    def retrieve_all_items():
        """Retrieves all data entries and 
        corresponding columns from Item table.
        """
        with create_connection() as conn:
            return conn.execute(select(Item))

炒作
忽略上面代码中的类和函数构造,魔术是一个简单的语句选择(Item)。其他用于结构,而conn.execute()是我们之前使用过的熟悉。

创建 DQL 类是为了封装所有选择查询表达式和数据库调用。function 返回所有 Item 条目以及所有列。retrieve_all_items

要检索唯一的 Item 条目,只需将 chainingconstructs 升级到现有构造。.where()select

db/scripts/items_el.py

class DQL:
    """Encapsulates database query language (DML)"""

    # codes from existing methods         

    @staticmethod
    def retrieve_item_by_id(id:int):
        """Retrieves a single item by it's id.

        - id <int> A unique identifier of an item.
        """
        statement = (
            select(Item)
            .where(Item.c.id==bindparam('id', type_=Integer))
        )
        with create_connection() as conn:
            result = conn.execute(statement, {'id': id})
            return result

上面代码段中的 SELECT 语句利用了传递表的(主键)列以实现特异性的构造。.where()idItem

小问题很简单,用于指定我们期望从用户那里获得的值和值的类型。在本例中,我们期待 anof 类型。这作为字典传递给第二个参数。bindparamidIntegerconn.execute

bindparam从 导入自sqlalchemy.sql

使用 SQLAlchemy 表达式语言插入

数据库 INSERT 语句用于填充数据库表。INSERT 是 SQL 中的数据操作语言 (DML) 子句。类的实例具有方法,以便于将数据插入到相应的表中。在数据插入时,我们要么指定我们拥有数据的列名,并将这些数据作为值提供给语句,要么为所有可用列提供数据,同时分解可用约束。sqlalchemy.Table.insert()

语句构造点

  1. 指定我们为其提供数据的表列或对所有列进行寻址
  2. 将数据作为值发送到语句
  3. 因子约束

db/scripts/items_el.py

class DML:
    """Encapsulates database manipulation language (DML)"""

    @staticmethod
    def add_item(name:str, category:str):
        """Adds a single item to Item table"""
        statement = Item.insert().values(name=name, category=category)
        with create_connection() as conn:
            conn.execute(statement)
            conn.commit()

Item.insert().values(name=name, category=category)上面的代码满足插入语句构造概述的所有要点。项目表有 3 列 ().列未在上面的代码片段中指定,因为它是自动递增的主键,默认情况下会自行填充。我们只提供列。我们也可以省略列,因为它是一个可为空的列,如果未提供任何内容,则默认为 None。也可以利用这些值并将其作为字典提供给函数的第二个参数。id, name & categoryidnamecategorycategorybindparamconn.execute

# every other code above

statement = Item.insert().values(
    name=bindparam('name', type_=String),
    category=bindparam('category', type_=String)
)
with create_connection() as conn:
    conn.execute(statement, {'name': name, 'category': category)

# every other code below

使用函数,一次只能插入一条 Item 记录。SQLAlchemy 允许插入多个项目,这些项目将转换为执行许多语句。add_item(...)

db/scripts/items_el.py

class DML:
    """Encapsulates database manipulation language (DML)"""

    # codes from existing methods 

    @staticmethod
    def add_items(payload:List[Dict[str, str]]):
        """Inserts multiple items to Item table

        - payload <list> new data to be added to
                         Item table. Each dict has
                         key mapped to the Item table
                         and it's corresponding value.
        """
        with create_connection() as conn:
            conn.execute(Item.insert(), payload)
            conn.commit()

add_items函数将一系列键值对作为参数。此参数用作函数调用的第二个参数。insert 语句不必指定任何列 withand,因此,序列有效负载中的键值对应具有所有不可为空的字段。在这种情况下,justkey 值对就足够了,因为列可以自行填充并且列可为空。conn.execute().values()nameidcategory

使用 SQLAlchemy 表达式语言删除

使用 DELETE 语句,可以从数据库表中删除单个、多个或所有记录。类实例有一个方法,可用于从表中删除现有记录。为了特异性,调用构造来标识记录。sqlalchemy.Table.delete().where()

db/scripts/items_el.py

class DML:
    """Encapsulates database manipulation language (DML)"""

    # code from existing methods

    @staticmethod
    def delete_item(item_id:int):
        """Deletes an item whose id is passed as a 
        parameter

        - item_id <int> Uniquely identifies an item
                        instance
        """
        with create_connection() as conn:
            statement = Item.delete().where(
                Item.c.id==bindparam('id', type_=Integer)
            )
            conn.execute(statement, {'id': item_id})
            conn.commit()

delete_item函数采用参数来标识要从项目表中删除的记录。转换为语句:项目表中删除所有记录。链接构造有助于指定要删除的给定记录。在这种情况下,项列用于记录查找。

标签:SQL,语言,sqlalchemy,函数,语句,DQL,操作
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有