当前位置:网站首页>Sqlachemy common operations
Sqlachemy common operations
2022-07-01 14:18:00 【A-L-Kun】
List of articles
SQLAchemy
1、 ORM frame
What is? ORM?
Relational object mapping
class -> surface object -> Record ( A line of data )When there is a corresponding relationship , No longer required SQL sentence , Instead, the operation : class 、 object
pythonThe next commonORMYesdjango orm、SQLAlchemyandpeewee
Concept :
db first: Generate classes according to the tables in the databasecode first: Create database tables from classes
2、 Get to know
2.1 Operation process

2.2 Basic use
stay models.py In file
Create tables and delete tables
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : models.py
# @time : 2022/6/8 0:00
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, INTEGER, String
Base = declarative_base() # Create a base class
# Database connection
engine = create_engine(
"mysql+pymysql://root:[email protected]:3306/flask1?charset=utf8", # database url
max_overflow=0, # Exceeds the maximum number of connections created outside the connection pool size
pool_size=5, # Connection pool size
pool_timeout=30, # There is no thread waiting time in the pool , Otherwise, the report will be wrong
pool_recycle=-1 # How long after a thread in the thread pool has a connection reset
) # By default, the connection pool
# Create table
class Users(Base):
__tablename__ = "users1" # set a table name
id = Column(INTEGER, primary_key=True, autoincrement=True)
name = Column(String(32))
extra = Column(String(32))
# # Create table , If the table already exists , No more
# Base.metadata.create_all(engine)
# # Delete table
# Base.metadata.drop_all(engine)
Add information to the table
Among others py In file
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : test.py
# @time : 2022/6/8 0:13
from sqlalchemy.orm import sessionmaker
import models
session = sessionmaker(bind=models.engine)() # Create connection
obj = models.Users(name="kun", extra="hello")
session.add(obj) # Add data to table
session.commit() # Commit transaction
2.3 Connect to database
SQLAlchemy Can't operate the database itself , Since it has to pymsql Third party plug-ins ,Dialect For and data API To communicate , Call different databases according to different configuration files API, So as to realize the operation of database , Such as :
MySQL-Python
mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
MySQL-Connector
mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
cx_Oracle
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
More on :http://docs.sqlalchemy.org/en/latest/dialects/index.html
2.4 Perform native SQL sentence
# Database connection
engine = create_engine("mysql+pymysql://root:[email protected]:3306/flask1?charset=utf8") # By default, the connection pool
cur = engine.execute("SELECT * FROM user1")
print(cur.fetchall())
3、 Create multiple tables
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : models.py
# @time : 2022/6/8 0:00
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
create_engine, Column, INTEGER, String,
DATETIME, # Create a column of storage time
ForeignKey, # Foreign key constraints
Index, # Create index
UniqueConstraint, # Create a union unique index
)
import datetime
Base = declarative_base() # Create a base class
# Database connection
engine = create_engine(
"mysql+pymysql://root:[email protected]:3306/flask1?charset=utf8", # database url
) # By default, the connection pool
# Create class table
class Classes(Base):
__tablename__ = "classes" # set a table name
id = Column(INTEGER, primary_key=True, autoincrement=True)
name = Column(String(32), nullable=False, unique=True)
# Student list , It has a one to many relationship with the class schedule
class Student(Base):
__tablename__ = "student"
id = Column(INTEGER, primary_key=True, autoincrement=True)
username = Column(String(32), nullable=False, unique=True)
password = Column(String(64), unique=False)
ctime = Column(DATETIME, default=datetime.datetime.now) # Creation time , Be careful now There is no need to put parentheses after , Otherwise, only the initialization time will be recorded , Not when the data is added
class_id = Column(INTEGER, ForeignKey("classes.id")) # Foreign key constraints
# Students' hobbies
class Hobby(Base):
__tablename__ = "hobby"
id = Column(INTEGER, primary_key=True)
caption = Column(String(50), default=" Basketball ")
from sqlalchemy.orm import relationship
cls = relationship("Classes", secondary="S_H", backref="stus") # Create a multi table Association , adopt cls Key to associate ,secondary It is a table that associates two tables ,backref, Reverse generation
# Many-to-many tables , That is to connect students with their hobbies
class S_H(Base):
__tablename__ = "s2h"
id = Column(INTEGER, primary_key=True, autoincrement=True)
stu_id = Column(INTEGER, ForeignKey("student.id"))
hob_id = Column(INTEGER, ForeignKey("hobby.id"))
__table_args__ = (
UniqueConstraint("stu_id", "hob_id", name="uin_stu_hob"), # Create a joint unique index for the two columns
# Index("in_stu_hob", "stu_id", "extra") # Create an index
)
if __name__ == '__main__':
# Create table , If the table already exists , No more
Base.metadata.create_all(engine)
# # Delete table
# Base.metadata.drop_all(engine)
4、 Additions and deletions
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : test.py
# @time : 2022/6/8 0:13
from sqlalchemy.orm import sessionmaker
import models
from sqlalchemy import text
session = sessionmaker(bind=models.engine)() # Connect to database
def add_data():
""" Add data """
# Single addition
cls = models.Classes(name='1 class ')
session.add(cls)
# Add more
objs = [
models.Classes(name='2 class '),
models.Classes(name='3 class ')
]
session.add_all(objs)
def del_data():
""" Delete data """
session.query(models.Classes).filter(models.Classes.id > 2).delete() # Specify conditions to delete data
def find_data():
""" Query data """
ret = session.query(models.Classes).all() # Get all the data
ret1 = session.query(models.Classes.name).all() # Get name data
ret2 = session.query(models.Classes).filter(models.Classes.name == "2 class 009009").all() # obtain 2 Class data
ret3 = session.query(models.Classes).filter_by(name="2 class 009009").first() # Get the data of class 2
ret4 = session.query(models.Classes).filter(text("id<:value and name=:name")).params(
# :value and :name For a placeholder , Use order_by Sort
value=224,
name="field"
).order_by(models.Classes.id)
ret5 = session.query(models.Classes).from_statement(text("SELECT * FROM classes WHERE name=:name")).params(
name="ed" # structure SQL sentence
)
print(ret5)
# Use subquery
ret6 = session.query(models.Classes).filter(models.Classes.id.in_(
session.query(models.Classes.id).filter_by(name="eee") # It is a subquery
)).all()
ret7 = session.query()
print(ret)
""" Linked table operation """
# Access to student information , And its class information
# Method 1
objs = session.query(models.Student.id, models.Student.username, models.Classes.name).join(models.Classes, isouter=True).all()
# Method 2
objs1 = session.query(models.Student).all()
""" # stay models.Student Add these two lines of code at the end , Automatically associate the database according to the foreign key from sqlalchemy.orm import relationship cls = relationship("Classes", backref="stus") # backref It is a reverse generation , That is, in Classes Add stus = relationship("Student") """
for item in objs1:
print(
item.id,
item.username,
item.cls, # This is the associated database , Can access its internal content
)
def up_data():
""" Modifying data """
session.query(models.Classes).filter(models.Classes.id >= 1).update({
models.Classes.name: models.Classes.name + "009",
# It's fine too "name": models.Classes.name + "009",
},
synchronize_session=False # Do not operate internally , It's a direct splice , If the value is "evaluate" Words , Will perform operations
)
# add_data()
# del_data()
# find_data()
# up_data()
session.commit() # Commit transaction
session.close()
5、 Common operations
# Conditions
# Query by a condition
ret = session.query(Users).filter_by(name='alex').all()
# id > 1 && name == "eric"
ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
# 1 <= id <= 3 && name == "eric"
ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
# id in (1, 3, 4)
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
# id not in (1, 3, 4)
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
# SELECT * FROM USERS WHERE id IN (SELECT id FROM USERS WHERE name = "eric")
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()
from sqlalchemy import and_, or_
# id > 3 && name == "eric"
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
# id < 2 || name == "eric"
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
# id < 2 || (name == "eric" && id > 3) || extra
ret = session.query(Users).filter(
or_(
Users.id < 2,
and_(Users.name == 'eric', Users.id > 3),
Users.extra != ""
)).all()
# wildcard
ret = session.query(Users).filter(Users.name.like('e%')).all()
ret = session.query(Users).filter(~Users.name.like('e%')).all()
# Limit
ret = session.query(Users)[1:2]
# Sort
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(
Users.name.desc(),
Users.id.asc() #
).all()
# grouping
from sqlalchemy.sql import func
ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
func.max(Users.id),
func.sum(Users.id),
func.min(Users.id)).group_by(Users.name).all()
ret = session.query(
func.max(Users.id),
func.sum(Users.id),
func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()
# Even the table
ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()
ret = session.query(Person).join(Favor).all()
ret = session.query(Person).join(Favor, isouter=True).all()
# Combine
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all()
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()
边栏推荐
- Après avoir été licencié pendant trois mois, l'entrevue s'est effondrée et l'état d'esprit a commencé à s'effondrer.
- 原来程序员搞私活这么赚钱?真的太香了
- App自动化测试开元平台Appium-runner
- [Jianzhi offer] 54 The k-th node of binary search tree
- 微服务大行其道的今天,Service Mesh是怎样一种存在?
- Applet - applet chart Library (F2 chart Library)
- [NLP] pre training model - gpt1
- Applet - multiple text line breaks in view
- What "hard core innovations" does Intel have in the first half of 2022? Just look at this picture!
- Research Report on the development trend and competitive strategy of the global diamond suspension industry
猜你喜欢

被裁三个月,面试到处碰壁,心态已经开始崩了

After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse

户外LED显示屏应该考虑哪些问题?

Build your own website (21)

That hard-working student failed the college entrance examination... Don't panic! You have another chance to counter attack!

Leetcode (69) -- square root of X
![[NLP] pre training model - gpt1](/img/bd/9803ad946b33159de51b93106a2151.png)
[NLP] pre training model - gpt1

QT学习管理系统

QT learning management system

Six years of technology iteration, challenges and exploration of Alibaba's globalization and compliance
随机推荐
MySQL日志
phpcms实现订单直接支付宝支付功能
This paper introduces an implementation scheme to enhance the favorite transaction code management tool in SAP GUI
【剑指 Offer】55 - II. 平衡二叉树
被裁三个月,面试到处碰壁,心态已经开始崩了
Research Report on the development trend and competitive strategy of the global powder filling machine industry
Research Report on the development trend and competitive strategy of the global aviation leasing service industry
Phpcms realizes the direct Alipay payment function of orders
SWT / anr problem - how to open binder trace (bindertraces) when sending anr / SWT
光环效应——谁说头上有光的就算英雄
Research Report on the development trend and competitive strategy of the global camera filter bracket industry
使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片,并存储到指定服务器
Research Report on the development trend and competitive strategy of the global facial wrinkle removal and beauty instrument industry
sqlilabs less9
Summary of leetcode's dynamic programming 5
Is it reasonable and safe for securities companies to open accounts for 10000 free securities? How to say
Today, with the popularity of micro services, how does service mesh exist?
【IoT毕设.下】STM32+机智云AIoT+实验室安全监控系统
Using CMD to repair and recover virus infected files
Halo effect - who says that those with light on their heads are heroes