一起来了解下SQLAlchemy吧

     上一篇我们了解了Flask的简单使用,相信小伙伴们已经都实现了自己第一个web程序,那接下来就让我们一起走进SQLAlchemy的世界吧,首先我们先解答下以下问题

1.SQLAlchemy是什么玩意?

SQLAlchemy是一个基于Python实现的ORM框架,那问题来了,啥叫ORM呀?

ORM定义: 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。

举个例子:

 比如我们需要在数据库中建立一张表名字叫student_info

idnameagescore
1xiaowei2599
2xiaohua24100

在程序中要使用对应数据库第三方的数据库操作,使用SQL的语句进行插入数据。使用ORM框架则是将表抽象为一个对象,一行数据就是代表一个学生,数据库字段iID,名字,年龄,分数则是这个学生的属性,只要我们构造这样一个stduent对象,并给这个对象赋值,然后ORM就会帮我们转换为和SQL操作一样的效果,进行了映射。

2.为什么要使用SQLAlchemy,有什么好处?

1.简单易于理解,通过建模后,表抽象为对象,让我们操作数据库变的简单,易于理解。

2.提高可用性,不知道小伙伴们在学习工作中遇到很多人为bug是因为不规范、冗余、风格不统一的SQL语句造成的,而使用SQLAlchemy正好可以避免这一点。

3.代码移植好,我们可能会遇到这种情况,我们项目中第一采用的是mysql数据库,后来因为某个原因需要更换为Postgresql数据库,这时候可能我们需要修改各种代码,而SQLAlchemy则只需要更换下数据库地址即可,是不是很方便呢

当然,简单方便的同时,也会带来些性能的损失

3.SQLAlchemy的使用

3.1 环境安装

pip install SQLAlchemy  安装即可

这里提供个小技巧给大家,当安装慢的时候可以采用阿里云的源pip install SQLAlchemy -i https://mirrors.aliyun.com/pypi/simple/

3.2 代码实战

还是以上表学生信息为例,首先进行数据建模

import sqlalchemy
from sqlalchemy import create_engine,func
from sqlalchemy.ext.declarative import declarative_base
#此行导入数据库字段相关类型
from sqlalchemy import Column,Integer,String,ForeignKey,DATE,DateTime,Text,Date,Time
from sqlalchemy.orm import sessionmaker,relationship

#构造一个基类
g_base = declarative_base()

#这个类即为一张表抽象的对象,继承基类
class student_info_tbl(g_base):
    __tablename__='student_info_tbl'
    #Integer代表数据类型,nullable表示是否能为空,unique是否能重复,primary_key是否为主键
    id = Column(Integer,nullable=False,unique=True,primary_key=True)
    name = Column(Text,nullable=True)
    age = Column(Integer,nullable=True)
    score = Column(Integer,nullable=False)

以上就完成了一张表的建模,接下来我们看下如何操作这张表

import sqlalchemy
from sqlalchemy import create_engine,func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,DATE,DateTime,Text,Date,Time
from sqlalchemy.orm import sessionmaker,relationship


#初始化数据库连接
def init_sql_engine(database,encode,isecho,max_over,poolsize,pooltimeout,poolrecycle):
    '''
    database:database url  ---exp postgresql://qj_box:1@127.0.0.1:5432/qjdb
    encode:exp 'utf-8'
    isecho:debug flag ---exp True/False
    '''
    sql_engine = create_engine(database,encoding=encode,
                                echo=isecho,max_overflow=max_over,
                                pool_size=poolsize,pool_timeout=pooltimeout,
                                pool_recycle=poolrecycle)

    return sql_engine

class db_tab_func:
    def __init__(self,sql_engine):
        #创建会话
        self.__session_class = sessionmaker(bind=sql_engine)

    def __del__(self):
        pass

    #插入数据,会根据对象类型自动转换
    def insert(self,element_list=[]):
        session = self.__session_class()
        result = session.add_all(element_list)
        session.commit()
        session.close()
        return result

    #根据名字查询
    def student_name_query(self,name):
        session = self.__session_class()
        element =  \ 
        #查询student_info_tbl,当名字为name时候匹配,first()则第一条,all()则同名全部    
        session.query(student_info_tbl).filter(student_info_tbl.name==name).first()
        session.close()
        return element

    #更新学生分数
    def student_score_update(self,name,score):
        session = self.__session_class()
        session.query(student_info_tbl).filter(student_info_tbl.name==name \
        ).update({"score":score})
        session.commit()
        session.close()

    #删除学生数据  
    def student_delete(self,name):
        session = self.__session_class()
        session.query(student_info_tbl).filter(student_info_tbl.name == name).delete()
        session.commit()
        session.close()

接下来我们看下怎么使用上面的API

if __name__=='__main__':
    sql_engine = init_sql_engine('postgresql://qj_box:1@127.0.0.1:5432/qjdb',
                                    'utf-8',False,0,5,30,-1)
    student_func = db_tab_func(sql_engine)

    element = student_info_tbl(id=1,name='xiaowei',age=25,score=99)
    element_list = [element]
   
    student_func.insert(element_list)
    student_func.student_name_query("xiaowei")
    student_func.student_score_update("xiaowei",100)
    student_func.student_delete("xiaowei")

以上就是SQLAlchemy的简单使用,小伙伴快动手试下吧

 

The SQLAlchemy Object Relational Mapper presents a method of associating user-defined Python classes with database tables, and instances of those classes (objects) with rows in their corresponding tables. It includes a sys- tem that transparently synchronizes all changes in state between objects and their related rows, called a unit of work, as well as a system for expressing database queries in terms of the user defined classes and their defined relationships between each other. The ORM is in contrast to the SQLAlchemy Expression Language, upon which the ORM is constructed. Whereas the SQL Expression Language, introduced in SQL Expression Language Tutorial, presents a system of representing the primitive constructs of the relational database directly without opinion, the ORM presents a high level and abstracted pattern of usage, which itself is an example of applied usage of the Expression Language. While there is overlap among the usage patterns of the ORM and the Expression Language, the similarities are more superficial than they may at first appear. One approaches the structure and content of data from the perspective of a user-defined domain model which is transparently persisted and refreshed from its underlying storage model. The other approaches it from the perspective of literal schema and SQL expression representations which are explicitly composed into messages consumed individually by the database. A successful application may be constructed using the Object Relational Mapper exclusively. In advanced situations, an application constructed with the ORM may make occasional usage of the Expression Language directly in certain areas where specific database interactions are required. The following tutorial is in doctest format, meaning each >>> line represents something you can type at a Python command prompt, and the following text represents the expected return value.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值