首页 技术 正文
技术 2022年11月14日
0 收藏 975 点赞 2,090 浏览 5495 个字

参考:

https://www.jianshu.com/p/0d234e14b5d3

1.Connecting

我们通过 create_engine() 来链接数据库,假设我们我们采用SQLite。

from sqlalchemy import create_engine
engine = create_engine('sqlite:///app.db',echo=True)

[文档片段]: create_engine() 的返回值是 Engine 的一个实例,Engine是database的核心接口,通过方言*来处理使用中的database和DBAPI的细节。

Q:Engine是什么?
片段:把Pool和Dialect链接在一起,以提供数据库的链接和行为的资源。
参照SQLAlchemy架构图,Engine通过Connection Pooling来链接数据库,然后通过Dialect执行SQL语句Q:方言(dialect)是什么?
Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API
说白了就是执行SQLQ:DBAPI是什么?
DB-API是一个规范,他定义了一系列必须的对象和数据库的存取方式。
理解一下,它就是一个规范。。。
SQLAlchemy架构图:
官方文档粗读 – Tutorial

[文档片段]:第一次执行 Engine.execute() 或者 Engine.connect() 的时候,Engine会对Database创建一个实际的DB-API链接,然后使用数据库发出SQL。

・就是一个链接(connect)和执行(execute)的过程

・文档说不会直接使用Engine,稍后会介绍其他东西,是什么呢?

  ※ 读到后面了,后面介绍了Session。Session关联了Engine,和数据库的对话交由Session来实现。

2.Declare a Mapping

[文档片段]:When using the ORM, the configurational process starts by describing the database tables we’ll be dealing with, and then by defining our own classes which will be mapped to those tables.

当使用ORM时,配置过程从描述数据库表开始,然后定义将映射到这些表的类。这两个任务怎么进行的呢?对,是使用 Declarative ,Declarative允许我们创建一个类去描述真实的数据库表,使它们之间建立联系。

Q:这一段说了啥?
ORM和普通的数据库表不同,但是ORM可以转换成数据库表。
那么怎么转化呢?通过Declarative
1.描述一下数据库表,怎么描述的呢?Emmm,研究中...
2.再定义一个类来映射到这个数据库表

[具体如何操作呢?]:

要使用这种映射关系,我们需要继承一个基类,这个基类就是 sqlalchemy.ext.declarative ,如下我们定义这个基类:

from sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()

之后我们就可以创建映射关系了,当然,我们可以创建多个映射关系,只要继承这个基类就行了。

  ※  这里的映射关系指ORM和真实的数据库表之间的映射

比如我们要创建一个用户表,怎么做呢?直接去看官方文档的例子吧 ~

[需要注意的点]:

1.这个类(比如说用户表类),至少得需要一个__tablename__属性

2.至少需要一个Column,还得有个主键

3.__repr__方法是可选的

[文档片段]:SQLAlchemy never makes any assumptions by itself about the table to which a class refers, including that it has no built-in conventions for names, datatypes, or constraints.   But this doesn’t mean boilerplate is required; instead, you’re encouraged to create your own automated conventions using helper functions and mixin classes, which is described in detail at Mixin and Custom Base Classes.

SQLAlchemy 不会对类引用的表做任何假设*,包括命名、数据格式、或者约束。我们鼓励使用帮助函数和混合类来创建自己的约定*,具体请查看Mixin and Custom Base Classes.

这tm说的啥!

3.Create a Schema

[文档片段]:With our User class constructed via the Declarative system, we have defined information about our table, known as table metadata. The object used by SQLAlchemy to represent this information for a specific table is called the Table object, and here Declarative has made one for us.

通过Declarative system构造了User类,这个类我们定义了关于表的信息,即元数据Metadata。

[文档片段]:The MetaData is a registry which includes the ability to emit a limited set of schema generation commands to the database. As our SQLite database does not actually have a users table present, we can use MetaData to issue CREATE TABLE statements to the database for all tables that don’t yet exist. Below, we call the MetaData.create_all() method, passing in our Engine as a source of database connectivity. We will see that special commands are first emitted to check for the presence of the users table, and following that the actual CREATE TABLE statement

MetaData是什么呢?它能够向Database发出一些有限的命令集合,那么问题来了,他能发出什么命令呢?

文档之后又说了,当我们的SQLite Database没有users表的时候,我们可以用MetaData发出 CREATE TABLE 命令去创建一个users表。

最后举了一个例子:通过调用 MetaData.create_all() 方法,把engine当做参数传进去,就能够执行一个CREATE TABLE的命令。

注意:

1.CREATE TABLE只有表不存在的时候才创建成功

2.在执行 MetaData.create_all() 之后才在硬盘上出现app.db文件,单独执行create_engine()方法是没有创建文件的

4.Create an Instance of the Mapped Class

关于__init__()方法要说一下

1.__init__()方法默认会将参数和数据库的字段相匹配。

比如:

ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')

2.当然你也可以自己重写__init__()方法。

5.Create a Session

[文档片段]:We’re now ready to start talking to the database. The ORM’s “handle” to the database is the Session. When we first set up the application, at the same level as our create_engine() statement, we define a Session class which will serve as a factory for new Session objects

Session是什么呢?直译是会话,它是和数据库通话的桥梁(句柄)。

step1:如何创建Session呢?

・用sessionmaker,在create_engine()同一级别下定义Session类,这个Session类作为一个工厂来生产新的Session对象。

step2:如何连接engine和session呢?

・ Session.configure(bind=engine)

step3:实例化Session

・ session = Session()

[文档片段]:The above Session is associated with our SQLite-enabled Engine, but it hasn’t opened any connections yet. When it’s first used, it retrieves a connection from a pool of connections maintained by the Engine, and holds onto it until we commit all changes and/or close the session object.

Session关联上了Engine,但是他还没有打开任何和Engine的链接。

当第一次使用Session时,它从Engine的连接池里获得一个连接,并且一直持续直到我们执行了commit或者关闭了session对象。

6.Adding and Updating Objects

・Building a Relationship

[文档片段]:The above class introduces the ForeignKey construct, which is a directive applied to Column that indicates that values in this column should be constrained to be values present in the named remote column.

总结了一下:

The above class introduces the ForeignKey construct,
上面的例子中使用了ForeignKey

witch is a directive applied to Column
这个ForeignKey是什么呢?
->它是应用于Column的指令
那么Column是什么呢?
->我理解的是Address类中的一个属性,也就是数据库中的一个字段
这句简单的说就是我定义了一个属性(一个字段)user_idthat indicates that values in this column should be constrained to be values present in the named remote column.
上面说了定义好了属性(字段)user_id,那么这个user_id有什么限定呢?
->user属性(字段)的值会受到约束,约束来自于另一个表
就是说我定义的这个user_id是和另外一张表有关系的

啊,本来是想说明relationship的,算了,写都写了。。。

[文档片段]:An additional relationship() directive is placed on the User mapped class under the attribute User.addresses.In both relationship() directives, the parameter relationship.back_populates is assigned to refer to the complementary attribute names; by doing so, each relationship() can make intelligent decision about the same relationship as expressed in reverse; on one side, Address.user refers to a User instance, and on the other side, User.addresses refers to a list of Address instances.

另外一个relationship定义在User表中,两个表都要写上relationship来表明之间的关系。

User表中: addresses = relationship( “Address”, order_by=Address.id, back_populates=”user”)

Address表中: user = relationship(“User”, back_populates=”addresses”)

[ 那么问题来了,这个back_populates是什么呢? ]

  ->这一句我没怎么读懂,大概就是back_populates是指向另一个关系表中的属性名,从上面的User表和Address表可以看出。

[ 那么这样做的效果是什么呢? ]

  ->能互相引用。。。在Address表中能引用User表实例,在User表中能引用Address表实例。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,991
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,505
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,349
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,134
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,766
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,844