Python/通过ORM框架-SQLAIchemy对数据库进行操作/01

一、什么是ORM框架?


  ORM指的是对象–关系映射(Object/Relation Mapping,简称ORM),随着面向对象的开发方法发展而产生。 面向对象的开发方法是当今企业应用开发环境中的主流开发方法。关系数据库是企业级应用环境中永久存放数据的主流数据库存储系统。 对象和关系数据是业务实体的两种表现形式,业务实体在内存中的表现为对象,在数据中表现的为关系数据。 内存中的对象之间存在关联和继承的关系,而在数据库中,关系数据无法直接表达多对多关联和继承的关系。 因此对象–关系映射系统一般以中间件的形式去存在。 主要实现程序对象到关系数据库中的数据映射。

1.1、ORM方法论基于三个核心的原则:
  • 简单性:以最基本的形式建模数据。
  • 传达性:数据库结构被任何人都能理解的语言文档化。
  • 精确性:基于数据模型创建正确标准化结构。
1.2、ORM包括以下四部分:
  • 一个对持久类对象进行CRUD操作的API
  • 一个语言或API用来规定与类和类属性相关的查询;
  • 一个规定mapping metadata的工具;
  • 一种技术可以让ORM的实现同事务对象一起进行dirty checking, lazy association fetching以及其他的优化操作。
  • ORM:及Object-Relational Mapping,把关系数据库的表结构映射到对象上

以上内容来自:https://www.jianshu.com/p/0ad18fdd7eed

二、SQLAIchemy:


在python中最有名的ORM架构就是SQLAIchemy,本章主要了解SQLAIchemy的基本使用。

2.1、安装SQLAIchemy:
pip install SQLAIchemy # 在这里不区分大小写,它自动会识别
2.2、创建CSDN_SQLAIchemy库

在本章将以CSDN_SQLAIchemy为例,使用SQLAIchemy对CSDN_SQLAIchemy库进行操作。

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mall               |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.001 sec)

MariaDB [(none)]> create database CSDN_SQLALchemy;
Query OK, 1 row affected (0.001 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| csdn_sqlalchemy    |
| information_schema |
| mall               |
| mysql              |
| performance_schema |
+--------------------+
5 rows in set (0.001 sec)

三、SQLAIchemy的初步使用:


在开始之前,需要先了解SQLAIchemy的一些初步使用方法,为了更好的理解后续内容:

declarative_base() 创建基类
class 数据类-table
create_ engine 数据库引擎连接数据库
session 创建会话,类似事务
object 创建数据库对象
query 各种查询的操作
3.1、导入SQLAIchemy相关的库,初始化DBSession

导入相关的库

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

初始化DBSession:

# 创建数据库引擎连接数据库.
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)

# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
session = DBSession()

‘数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名’
echo = True 表示输出日志
create_engine()用来初始化数据库连接。SQLAlchemy用一个字符串表示连接信息:

3.2、创建一个user表:

了解declarative_base元类:
Construct a base class for declarative class definitions.

The new base class will be given a metaclass that produces appropriate :class:~sqlalchemy.schema.Table objects and makes the appropriate :func:~sqlalchemy.orm.mapper calls based on the information provided declaratively in the class and any subclasses of the class.
(为声明性类定义构造基类, 新的基类将被赋予一个元类,这个元类将生成:class:sqlalchemy.schema。表对象,并使适当的:func:~sqlalchemy.orm。基于类和类的任何子类中声明性提供的信息调用mapper。)

可以理解为有一个叫declarative_base的元类,为声明性类定义构造基类,在创建表的时候继承这个基类,就可以自定义表的一些结构,如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column(id, Integer, primary_key=True)
    name = Column(name, String(30), unique=True)
    password = Column(password, String(30))


# 创建数据库引擎连接数据库.
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)

# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
session = DBSession()

创建表:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(30), unique=True)
    password = Column('password', String(30))

# 创建表操作
inherit_db.metadata.create_all(engine)

# ------------------------以下为运行日志输出--------------------

2019-05-02 18:25:36,642 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-05-02 18:25:36,643 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,644 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-05-02 18:25:36,644 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,646 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-05-02 18:25:36,646 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,647 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-05-02 18:25:36,648 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,651 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-05-02 18:25:36,651 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,652 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-05-02 18:25:36,652 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,653 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_bin AS anon_1
2019-05-02 18:25:36,653 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,656 INFO sqlalchemy.engine.base.Engine DESCRIBE `csdn_users`
2019-05-02 18:25:36,656 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,667 INFO sqlalchemy.engine.base.Engine ROLLBACK
2019-05-02 18:25:36,669 INFO sqlalchemy.engine.base.Engine
CREATE TABLE csdn_users (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name VARCHAR(30),
        password VARCHAR(30),
        PRIMARY KEY (id),
        UNIQUE (name)
)


2019-05-02 18:25:36,669 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 18:25:36,689 INFO sqlalchemy.engine.base.Engine COMMIT

补充 : metadata主要用于保存表结构,连接字符串等数据,是一个多表共享的对象,metadata.create_all(engine) #是来创建表,这个操作是安全的操作,会先判断表是否存在。

查看表:
Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第1张图片在创建一个Blog表:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(30), unique=True)
    password = Column('password', String(30))


class Blog(inherit_db):
    __tablename__ = "blog_user"

    id = Column('id', Integer, primary_key=True)
    blog_name = Column('blog_name', String(30), unique=True)
    blog_article = Column('blog_article', String(30))


# 创建表操作
inherit_db.metadata.create_all(engine)

Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第2张图片若指定没有的库,创建表如下:
Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第3张图片

3.3、对csdn_users表&blog_user进行插入数据操作:

目前已经建立好表了,表结构有三列,分别为id,name, password, 但是建立表之后却没有值,所以需要进行插入值得操作:

DBSession = sessionmaker(bind=engine)
session = DBSession()

通过sessionmake方法创建一个Session工厂,然后在调用工厂的方法来实例化一个Session对象

对csdn_users表插入数据:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(30), unique=True)
    password = Column('password', String(30))


class Blog(inherit_db):
    __tablename__ = "blog_user"

    id = Column('id', Integer, primary_key=True)
    blog_name = Column('blog_name', String(30), unique=True)
    blog_article = Column('blog_article', String(30))


# 创建表操作
# inherit_db.metadata.create_all(engine)

# 插入数据操作
user1 = Users(id='1', name='yankai', password='pwd123')
user2 = Users(id='2', name='zhangsan', password='123com')
user3 = Users(id='3', name='lisi', password='123456ok')

session.add_all([user1, user2, user3])
session.commit()
session.close()

-----------------------------以下为日志输出信息---------------------------
2019-05-02 19:11:32,464 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-05-02 19:11:32,464 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,468 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-05-02 19:11:32,468 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,469 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-05-02 19:11:32,469 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,471 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-05-02 19:11:32,471 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,472 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-05-02 19:11:32,472 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,474 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-05-02 19:11:32,474 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,475 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_bin AS anon_1
2019-05-02 19:11:32,476 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:11:32,477 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-05-02 19:11:32,479 INFO sqlalchemy.engine.base.Engine INSERT INTO csdn_users (id, name, password) VALUES (%(id)s, %(name)s, %(password)s)
2019-05-02 19:11:32,479 INFO sqlalchemy.engine.base.Engine ({'id': '1', 'name': 'yankai', 'password': 'pwd123'}, {'id': '2', 'name': 'zhangsan', 'password': '123com'}, {'id': '3', 'name': 'lisi', 'password': '123456ok'})
2019-05-02 19:11:32,483 INFO sqlalchemy.engine.base.Engine COMMIT

查看csdn_users表数据:
Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第4张图片以此类推,blog_user 插入数据:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(30), unique=True)
    password = Column('password', String(30))


class Blog(inherit_db):
    __tablename__ = "blog_user"

    id = Column('id', Integer, primary_key=True)
    blog_name = Column('blog_name', String(30), unique=True)
    blog_article = Column('blog_article', String(30))


# 创建表操作
# inherit_db.metadata.create_all(engine)

# 插入数据操作
user1 = Blog(id='1', blog_name='yankerp', blog_article='python_sqlalchemy')
user2 = Blog(id='2', blog_name='zhangsan', blog_article='Linux集群架构')
user3 = Blog(id='3', blog_name='wangwu', blog_article='shell脚本编程')

session.add_all([user1, user2, user3])
session.commit()
session.close()

---------------------------以下为日志输出信息---------------------------------
2019-05-02 19:15:04,488 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-05-02 19:15:04,488 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,489 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-05-02 19:15:04,489 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,490 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-05-02 19:15:04,490 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,492 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-05-02 19:15:04,492 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,493 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-05-02 19:15:04,493 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,494 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-05-02 19:15:04,494 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,495 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_bin AS anon_1
2019-05-02 19:15:04,496 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:15:04,497 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-05-02 19:15:04,498 INFO sqlalchemy.engine.base.Engine INSERT INTO blog_user (id, blog_name, blog_article) VALUES (%(id)s, %(blog_name)s, %(blog_article)s)
2019-05-02 19:15:04,498 INFO sqlalchemy.engine.base.Engine ({'id': '1', 'blog_name': 'yankerp', 'blog_article': 'python_sqlalchemy'}, {'id': '2', 'blog_name': 'zhangsan', 'blog_article': 'Linux集群架构
'}, {'id': '3', 'blog_name': 'wangwu', 'blog_article': 'shell脚本编程'})
2019-05-02 19:15:04,507 INFO sqlalchemy.engine.base.Engine COMMIT

查看表数据:
Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第5张图片如果不标注ID 插入数据时会怎样?
原表数据:

MariaDB [csdn_sqlalchemy]> select * from csdn_users;
+----+----------+----------+
| id | name     | password |
+----+----------+----------+
|  1 | yankai   | pwd123   |
|  2 | zhangsan | 123com   |
|  3 | lisi     | 123456ok |
+----+----------+----------+
3 rows in set (0.001 sec)

MariaDB [csdn_sqlalchemy]>

不指定id插入:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(30), unique=True)
    password = Column('password', String(30))


class Blog(inherit_db):
    __tablename__ = "blog_user"

    id = Column('id', Integer, primary_key=True)
    blog_name = Column('blog_name', String(30), unique=True)
    blog_article = Column('blog_article', String(30))


# 创建表操作
# inherit_db.metadata.create_all(engine)

# 插入数据操作
# user1 = Blog(id='1', blog_name='yankerp', blog_article='python_sqlalchemy')
# user2 = Blog(id='2', blog_name='zhangsan', blog_article='Linux集群架构')
# user3 = Blog(id='3', blog_name='wangwu', blog_article='shell脚本编程')
# session.add_all([user1, user2, user3])

user = Users(name='csdn', password='csdnisok')
session.add(user)
session.commit()
session.close()

2019-05-02 19:25:16,207 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2019-05-02 19:25:16,207 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,208 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2019-05-02 19:25:16,210 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,211 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2019-05-02 19:25:16,211 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,212 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = 'utf8mb4' and `Collation` = 'utf8mb4_bin'
2019-05-02 19:25:16,212 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,214 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS CHAR(60)) AS anon_1
2019-05-02 19:25:16,214 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,215 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS CHAR(60)) AS anon_1
2019-05-02 19:25:16,215 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,216 INFO sqlalchemy.engine.base.Engine SELECT CAST('test collated returns' AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_bin AS anon_1
2019-05-02 19:25:16,216 INFO sqlalchemy.engine.base.Engine {}
2019-05-02 19:25:16,218 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-05-02 19:25:16,220 INFO sqlalchemy.engine.base.Engine INSERT INTO csdn_users (name, password) VALUES (%(name)s, %(password)s)
2019-05-02 19:25:16,220 INFO sqlalchemy.engine.base.Engine {'name': 'csdn', 'password': 'csdnisok'}
2019-05-02 19:25:16,221 INFO sqlalchemy.engine.base.Engine COMMIT

自增:
Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第6张图片结合表,回顾内容:
Python/通过ORM框架-SQLAIchemy对数据库进行操作/01_第7张图片

查询操作将在下一章~

本章完整代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/2 18:26
# @Author  : YanZanG
# @File    : SQLAIchemy
# @Function: -----------

from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

inherit_db = declarative_base()
engine = create_engine('mysql+pymysql://root:111111@localhost:3306/csdn_sqlalchemy', echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()


class Users(inherit_db):
    __tablename__ = "csdn_users"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(30), unique=True)
    password = Column('password', String(30))

user = Users(name='csdn', password='csdnisok')
session.add(user)
session.commit()
session.close()

本文为个人学习总结,及个人笔记, 同时希望对您有所帮助,再见~

你可能感兴趣的:(Python,SQL)