SQLAlchemy ORM example introduction to python
1. Introduction to ORM
ORM's full name in English is object relational mapping, which is an object mapping relationship program. Simply put, in our object-oriented programs like Python, everything is an object, but we use All databases are relational. In order to ensure consistent usage habits, the object model of the programming language and the relational model of the database are mapped through ORM, so that we can directly use the programming language when operating the database using the programming language. You can just operate the object model without using SQL language directly.
Advantages of ORM:
Hidden data access details, "closed" universal database interaction, the core of ORM. It makes our common database interactions simple and easy, without having to think about damn SQL statements at all. Rapid development comes from this.
ORM makes it simple and easy for us to construct a solidified data structure.
Disadvantages:
Inevitably, automation means mapping and association management at the expense of performance (in the early days, this was all What people like ORM have in common). Various current ORM frameworks are trying to use various methods to alleviate this problem (LazyLoad, Cache), and the effect is still very significant.
2. SQLAlchemy Framework and Database API
In Python, the most famous ORM framework is SQLAlchemy. Users include well-known companies or applications such as openstack\Dropbox. The main user list is http://www.php.cn/
. You need to map the tables in the database into classes yourself. Then it can be called through the object. SQLAlchemy not only supports MYSQL, but also Oracle, etc.
Dialect is used to communicate with the data API and call different database APIs according to different configuration files to achieve operations on the database:
1 2 3 4 5 6 7 8 9 10 11 |
|
Install SQLAlchemy:
1 |
|
3. Connect to the database and query
1 2 3 4 5 6 7 |
|
Output:
1 |
|
4. Create tables
Create user and color tables: When creating tables, they need to be bound to instances of MetaData.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
View the created table:
5. Add, delete, modify and check
1. Let’s understand it first Add, delete, and modify query of native sql statements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
2. Add, delete, and modify query through SQLAlchemy (important):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
Screenshot of operation results:
6. Foreign key association
1. Create the host table hosts and the grouping table group, and establish an association, that is, one group can correspond to multiple hosts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
View results:
Problem: When viewing the newly created group table structure or querying from the group table, you will find that desc group; select * from group will expose errors. !!(Why this error occurs may be caused by some relationship between group and database, eg: group by... I guess)
Solution: Use desc zcl.group; select * from zcl.group; (zcl is the database name)
2. After creating the table, you need to create data in the table. Next, create data in the hosts table and group table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
After testing: Although no errors are exposed during runtime, the association is unsuccessful, as shown below:
3. Now the problem comes again. The group_id in the hosts table is empty!! This is definitely not possible. Now how to make group_id not empty without deleting the hosts table data (eg: make group_id 4 and establish association with g4)?? The following code can be used:
1 2 3 |
|
4. Question: How to get the group_id associated with the host??
1 2 3 |
|
Okay, I admit it The question is too simple. Through the above code, find the host object h, then h.group_id is the answer. The next question is the key point.
5. 此时可以获取已经关联的group_id,但如何获取已关联的组的组名??
1 |
|
嗯,你是初学者,你当然会说通过过h.group.name就可以找到与主机关联的组名! BUT,这是不行的,会曝错,因为Host类根本就没有group属性!!
解决方法:
first:
1 |
|
second:
在Host类中加入group = relationship("Group"):
1 2 3 4 5 6 |
|
此时再用print(h.group.name)就不会曝错啦!!
6. 哈哈,问题还没完呢。 前面已经实现:通过主机可查看对应组名,那么如何实现通过组名查看对应的主机??
经过前面5个点的历练,你已成为小小的老司机了,于是你很自信地说: 和第5个点一样,在Group类中加入hosts = relationship("Host");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
7. 通过上面的两句代码可实现双向关联。但必须在两个表都加上一句代码才行,有没有办法只用一句代码就实现双向关联?? 当然有,老司机会这么做:
在Host类中加入下面这句代码,即可实现双向关联:
1 |
|
八、合并查询join
合并查询分为: inner join、left outer join、right outer join、full outer join
下面的例子可以让你完全理解join: http://stackoverflow.com/questions/38549/what-is-the-difference-between-inner-join-and-outer-join
关于join的原生sql操作:
在SQLAlchemy实现sql.join:
1 2 |
|
九、分类聚合group by
group by是啥意思呢? 我说下我的理解吧,group即分组,by为通过;合起来即: 通过XX分组;
举个例子吧,现在有两张表,分别是主机表与分组表。两表已经通过group_id建立关联,分组表中有4个数据,分别为g1,g2,g3,g4; id分别为1,2,3,4; 而主机表有3个数据,group_id分别为4,3,4; id分别为1,2,4; 现在对hosts表执行group by命令,进行分类聚合。
具体请看下图:
对应SQLAlchemy语句:
1 2 |
|
对应SQLAlchemy语句:
1 2 3 4 5 |
|
十、多对多关联
多对多关联,即: 一个主机h1可对应在多个组(g1,g2),一个组(g1)可对应多个主机(h1,h2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
虽然有了中间表,但如果想查看一个组对应的所有主机名或者一个主机对应的所有组,还是需要Group/Host与中间表进行一系列的关联操作(join~), 但SqlAlchemy简化了关联操作!!
调用下面命令便会自动关联中间表:
1 2 |
|
SQLAlchemy是如何实现多对多关联的??
1. 建立中间表,关联其它两个表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
2. 在Host表(或Group表)指定中间表的实例,加上backref就不用在Group表中指定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
3. 创建组与主机
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
4. 建立关联与查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
测试截图:
查看表结构:
查看表内容:
查看第三方表:
完整例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
更多python之SQLAlchemy ORM示例介绍相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
