当前位置:Gxlcms > 数据库问题 > SQLalchemy基本使用

SQLalchemy基本使用

时间:2021-07-01 10:21:17 帮助过:11人阅读

+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...]

  基本操作:

  1.链接数据库

技术分享图片
 1 import time
 2 import threading
 3 import sqlalchemy
 4 from sqlalchemy import create_engine
 5 from sqlalchemy.engine.base import Engine
 6 #ok1为数据库名称
 7 engine = create_engine(
 8     "mysql+pymysql://root:123@localhost:3306/ok1?charset=utf8",
 9     max_overflow=0,  # 超过连接池大小外最多创建的连接
10     pool_size=5,  # 连接池大小
11     pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
12     pool_recycle=-1, # 多久之后对线程池中的线程进行一次连接的回收(重置)
13     echo=True  # 显示执行的所有SQL语句
14 )
连接数据库

  取完数据自动关闭游标

技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 import sqlalchemy
 6 from sqlalchemy import create_engine
 7 from sqlalchemy.engine.base import Engine
 8 
 9 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=0, pool_size=5)
10 
11 
12 def task(arg):
13     conn = engine.contextual_connect()
14     with conn:
15         cur = conn.execute(
16             "select * from t1"
17         )
18         result = cur.fetchall()
19         print(result)
20 
21 
22 for i in range(20):
23     t = threading.Thread(target=task, args=(i,))
24     t.start()
View Code

  2. 执行原生sql语句

技术分享图片
 1 import time
 2 import threading
 3 import sqlalchemy
 4 from sqlalchemy import create_engine
 5 from sqlalchemy.engine.base import Engine
 6  
 7 engine = create_engine(
 8 "mysql+pymysql://root:123@127.0.0.1:3306/t1?charset=utf8",
 9 max_overflow=0, # 超过连接池大小外最多创建的连接
10 pool_size=5, # 连接池大小
11 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
12 pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
13 )
14  
15  
16 def task(arg):
17 conn = engine.raw_connection()
18 cursor = conn.cursor()
19 cursor.execute(
20 "select * from book"
21 )
22 result = cursor.fetchall()
23 cursor.close()
24 conn.close()
25  
26  
27 for i in range(10):
28 t = threading.Thread(target=task, args=(i,))
29 t.start()
View Code 技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 import sqlalchemy
 6 from sqlalchemy import create_engine
 7 from sqlalchemy.engine.base import Engine
 8 from sqlalchemy.engine.result import ResultProxy
 9 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=0, pool_size=5)
10 
11 
12 def task(arg):
13     cur = engine.execute("select * from t1")
14     result = cur.fetchall()
15     cur.close()
16     print(result)
17 
18 
19 for i in range(20):
20     t = threading.Thread(target=task, args=(i,))
21     t.start()
View Code

  3.ORM使用

   a.表的创建

技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import datetime
 4 from sqlalchemy import create_engine
 5 from sqlalchemy.ext.declarative import declarative_base
 6 from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
 7 
 8 Base = declarative_base()
 9 
10 
11 class Users(Base):
12     __tablename__ = users
13 
14     id = Column(Integer, primary_key=True)
15     name = Column(String(32), index=True, nullable=False)
16     # email = Column(String(32), unique=True)
17     # ctime = Column(DateTime, default=datetime.datetime.now)
18     # extra = Column(Text, nullable=True)
19 
20     __table_args__ = (
21         # UniqueConstraint(‘id‘, ‘name‘, name=‘uix_id_name‘),
22         # Index(‘ix_id_name‘, ‘name‘, ‘email‘),
23     )
24 
25 
26 def init_db():
27     """
28     根据类创建数据库表
29     :return: 
30     """
31     engine = create_engine(
32         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
33         max_overflow=0,  # 超过连接池大小外最多创建的连接
34         pool_size=5,  # 连接池大小
35         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
36         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
37     )
38 
39     Base.metadata.create_all(engine)
40 
41 
42 def drop_db():
43     """
44     根据类删除数据库表
45     :return: 
46     """
47     engine = create_engine(
48         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
49         max_overflow=0,  # 超过连接池大小外最多创建的连接
50         pool_size=5,  # 连接池大小
51         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
52         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
53     )
54 
55     Base.metadata.drop_all(engine)
56 
57 if __name__ == __main__:
58     drop_db()
59     init_db()
60 
61 创建单表
单表 技术分享图片
  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 import datetime
  4 from sqlalchemy import create_engine
  5 from sqlalchemy.ext.declarative import declarative_base
  6 from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
  7 from sqlalchemy.orm import relationship
  8 
  9 Base = declarative_base()
 10 
 11 
 12 # ##################### 单表示例 #########################
 13 class Users(Base):
 14     __tablename__ = users
 15 
 16     id = Column(Integer, primary_key=True)
 17     name = Column(String(32), index=True)
 18     age = Column(Integer, default=18)
 19     email = Column(String(32), unique=True)
 20     ctime = Column(DateTime, default=datetime.datetime.now)
 21     extra = Column(Text, nullable=True)
 22 
 23     __table_args__ = (
 24         # UniqueConstraint(‘id‘, ‘name‘, name=‘uix_id_name‘),
 25         # Index(‘ix_id_name‘, ‘name‘, ‘extra‘),
 26     )
 27 
 28 
 29 class Hosts(Base):
 30     __tablename__ = hosts
 31 
 32     id = Column(Integer, primary_key=True)
 33     name = Column(String(32), index=True)
 34     ctime = Column(DateTime, default=datetime.datetime.now)
 35 
 36 
 37 # ##################### 一对多示例 #########################
 38 class Hobby(Base):
 39     __tablename__ = hobby
 40     id = Column(Integer, primary_key=True)
 41     caption = Column(String(50), default=篮球)
 42 
 43 
 44 class Person(Base):
 45     __tablename__ = person
 46     nid = Column(Integer, primary_key=True)
 47     name = Column(String(32), index=True, nullable=True)
 48     hobby_id = Column(Integer, ForeignKey("hobby.id"))
 49 
 50     # 与生成表结构无关,仅用于查询方便
 51     hobby = relationship("Hobby", backref=pers)
 52 
 53 
 54 # ##################### 多对多示例 #########################
 55 
 56 class Server2Group(Base):
 57     __tablename__ = server2group
 58     id = Column(Integer, primary_key=True, autoincrement=True)
 59     server_id = Column(Integer, ForeignKey(server.id))
 60     group_id = Column(Integer, ForeignKey(group.id))
 61 
 62 
 63 class Group(Base):
 64     __tablename__ = group
 65     id = Column(Integer, primary_key=True)
 66     name = Column(String(64), unique=True, nullable=False)
 67 
 68     # 与生成表结构无关,仅用于查询方便
 69     servers = relationship(Server, secondary=server2group, backref=groups)
 70 
 71 
 72 class Server(Base):
 73     __tablename__ = server
 74 
 75     id = Column(Integer, primary_key=True, autoincrement=True)
 76     hostname = Column(String(64), unique=True, nullable=False)
 77 
 78 
 79 def init_db():
 80     """
 81     根据类创建数据库表
 82     :return: 
 83     """
 84     engine = create_engine(
 85         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
 86         max_overflow=0,  # 超过连接池大小外最多创建的连接
 87         pool_size=5,  # 连接池大小
 88         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
 89         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
 90     )
 91 
 92     Base.metadata.create_all(engine)
 93 
 94 
 95 def drop_db():
 96     """
 97     根据类删除数据库表
 98     :return: 
 99     """
100     engine = create_engine(
101         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
102         max_overflow=0,  # 超过连接池大小外最多创建的连接
103         pool_size=5,  # 连接池大小
104         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
105         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
106     )
107 
108     Base.metadata.drop_all(engine)
109 
110 
111 if __name__ == __main__:
112     drop_db()
113     init_db()
114 
115 创建多个表并包含Fk、M2M关系
关联表,fk,m2m

  b.数据库的操作

技术分享图片
 1 from sqlalchemy.orm import sessionmaker
 2 from sqlalchemy import create_engine
 3 from models import Users,Person,Hobby
 4 engine = create_engine(
 5         "mysql+pymysql://root:123@localhost:3306/ok1?charset=utf8",
 6         max_overflow=0,  # 超过连接池大小外最多创建的连接
 7         pool_size=5,  # 连接池大小
 8         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
 9         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
10 )
11 Session = sessionmaker(bind=engine)
12 # 每次执行数据库操作时,都需要创建一个session,申请一个连接
13 session = Session()
14 # ############# 执行ORM操作 #############
15 # obj1 = Users(name="xxx")
16 # obj2 = Users(name="yyy")
17 # session.add(obj1)
18 # session.add(obj2)
19 # 增加多个项目,用add_all
20 # session.add_all([
21 #         Users(name="aaa"),
22 #         Users(name="bbb")
23 # ])
24 # 提交事务
25 # session.commit()
26 from sqlalchemy import and_, or_
27 ret = session.query(Person).join(Hobby,Person.hobby_id==Hobby.id,isouter=True)
28 # ret = session.query(Person).join(Hobby,and_(Person.hobby_id==Hobby.id,Person.id >2),isouter=True)
29 print(ret)
30 # 关闭session
31 session.close()
简单查询 技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 
 6 from sqlalchemy.ext.declarative import declarative_base
 7 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 8 from sqlalchemy.orm import sessionmaker, relationship
 9 from sqlalchemy import create_engine
10 from db import Users
11 
12 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
13 Session = sessionmaker(bind=engine)
14 
15 
16 def task(arg):
17     session = Session()
18 
19     obj1 = Users(name="alex1")
20     session.add(obj1)
21 
22     session.commit()
23 
24 
25 for i in range(10):
26     t = threading.Thread(target=task, args=(i,))
27     t.start()
28 
29 多线程执行示例
多线程添加实例 技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 
 6 from sqlalchemy.ext.declarative import declarative_base
 7 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 8 from sqlalchemy.orm import sessionmaker, relationship
 9 from sqlalchemy import create_engine
10 from sqlalchemy.sql import text
11 
12 from db import Users, Hosts
13 
14 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
15 Session = sessionmaker(bind=engine)
16 
17 session = Session()
18 
19 # ################ 添加 ################
20 """
21 obj1 = Users(name="wupeiqi")
22 session.add(obj1)
23 
24 session.add_all([
25     Users(name="wupeiqi"),
26     Users(name="alex"),
27     Hosts(name="c1.com"),
28 ])
29 session.commit()
30 """
31 
32 # ################ 删除 ################
33 """
34 session.query(Users).filter(Users.id > 2).delete()
35 session.commit()
36 """
37 # ################ 修改 ################
38 """
39 session.query(Users).filter(Users.id > 0).update({"name" : "099"})
40 session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False)
41 session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")
42 session.commit()
43 """
44 # ################ 查询 ################
45 """
46 r1 = session.query(Users).all()
47 r2 = session.query(Users.name.label(‘xx‘), Users.age).all()
48 r3 = session.query(Users).filter(Users.name == "alex").all()
49 r4 = session.query(Users).filter_by(name=‘alex‘).all()
50 r5 = session.query(Users).filter_by(name=‘alex‘).first()
51 r6 = session.query(Users).filter(text("id"""
52 
53 
54 session.close()
55 
56 基本增删改查示例
基本增删改查

ps:sqlalchemy session 执行 delete 时 synchronize_session 策略

技术分享图片
 1 False
 2     不同步 session,如果被删除的 objects 已经在 session 中存在,在 session commit 或者 expire_all 之前,这些被删除的对象都存在 session 中。
 3 
 4     不同步可能会导致获取被删除 objects 时出错。
 5 
 6 fatch
 7     删除之前从 db 中匹配被删除的对象并保存在 session 中,然后再从 session 中删除,这样做是为了让 session 的对象管理 identity_map 得知被删除的对象究竟是哪些以便更新引用关系。
 8 
 9  evaluate
10     默认值。根据当前的 query criteria 扫描 session 中的 objects,如果不能正确执行则抛出错误,这句话也可以理解为,如果 session 中原本就没有这些被删除的 objects,扫描当然不会发生匹配,相当于匹配未正确执行。
11 
12 注意这里报错只会在特定 query criteria 时报错,比如 in 操作。
相关参数含义 技术分享图片
 1 # 条件
 2 ret = session.query(Users).filter_by(name=alex).all()
 3 ret = session.query(Users).filter(Users.id > 1, Users.name == eric).all()
 4 ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == eric).all()
 5 ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
 6 ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
 7 ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name=eric))).all()
 8 from sqlalchemy import and_, or_
 9 ret = session.query(Users).filter(and_(Users.id > 3, Users.name == eric)).all()
10 ret = session.query(Users).filter(or_(Users.id < 2, Users.name == eric)).all()
11 ret = session.query(Users).filter(
12     or_(
13         Users.id < 2,
14         and_(Users.name == eric, Users.id > 3),
15         Users.extra != ""
16     )).all()
17 
18 
19 # 通配符
20 ret = session.query(Users).filter(Users.name.like(e%)).all()
21 ret = session.query(Users).filter(~Users.name.like(e%)).all()
22 
23 # 限制
24 ret = session.query(Users)[1:2]
25 
26 # 排序
27 ret = session.query(Users).order_by(Users.name.desc()).all()
28 ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()
29 
30 # 分组
31 from sqlalchemy.sql import func
32 
33 ret = session.query(Users).group_by(Users.extra).all()
34 ret = session.query(
35     func.max(Users.id),
36     func.sum(Users.id),
37     func.min(Users.id)).group_by(Users.name).all()
38 
39 ret = session.query(
40     func.max(Users.id),
41     func.sum(Users.id),
42     func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()
43 
44 # 连表
45 
46 ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()
47 
48 ret = session.query(Person).join(Favor).all()
49 
50 ret = session.query(Person).join(Favor, isouter=True).all()
51 
52 
53 # 组合
54 q1 = session.query(Users.name).filter(Users.id > 2)
55 q2 = session.query(Favor.caption).filter(Favor.nid < 2)
56 ret = q1.union(q2).all()
57 
58 q1 = session.query(Users.name).filter(Users.id > 2)
59 q2 = session.query(Favor.caption).filter(Favor.nid < 2)
60 ret = q1.union_all(q2).all()
61 
62 常用操作
常用操作 技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 
 6 from sqlalchemy.ext.declarative import declarative_base
 7 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 8 from sqlalchemy.orm import sessionmaker, relationship
 9 from sqlalchemy import create_engine
10 from sqlalchemy.sql import text
11 from sqlalchemy.engine.result import ResultProxy
12 from db import Users, Hosts
13 
14 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
15 Session = sessionmaker(bind=engine)
16 
17 session = Session()
18 
19 # 查询
20 # cursor = session.execute(‘select * from users‘)
21 # result = cursor.fetchall()
22 
23 # 添加
24 cursor = session.execute(insert into users(name) values(:value),params={
                        
                    

人气教程排行