一、数据库连接池
python用于实现数据库连接池的模块是DBUntils
DBUntils有两种模式,一种是PersistentDB,一种是PooledDB
1、PersistentDB
该模式,会为每一个线程创建一个连接,创建的连接只可以给该线程使用,不能给其他线程使用,线程调用close方法后,连接会放到连接池,等待该线程的再次使用,直到线程终止时,连接才会关闭。这个模式,需要自己控制线程数量
#-*-coding:utf-8 -*-
importpymysqlfrom DBUtils.PersistentDB importPersistentDBPOOL=PersistentDB(
creator=pymysql,#使用链接数据库的模块
maxusage=None, #一个链接最多被重复使用的次数,None表示无限制
setsession=[], #开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
ping=0,#ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
closeable=False,#如果为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭链接。如果为True时, conn.close()则关闭链接,那么再次调用pool.connection时就会报错,因为已经真的关闭了连接(pool.steady_connection()可以获取一个新的链接)
threadlocal=local, #如果为none,用默认的threading.Loacl对象,否则可以自己封装一个local对象进行替换
host='127.0.0.1',
port=3306,
user='root',
password='root',
database='pooldb',
charset='utf8')deffunc():
conn=POOL.connection(shareable=False)
cursor=conn.cursor()
cursor.execute('select * from tb1')
result=cursor.fetchall()
cursor.close()
conn.close()func()
2、PooledDB
该模式下,是创建一批连接到连接池,供所有线程共享使用,一般都推荐用这种模式
#-*-coding:utf-8 -*-
importpymysqlfrom DBUtils.PooledDB importPooledDB
POOL=PooledDB(
creator=pymysql, #使用链接数据库的模块
maxconnections=6, #连接池允许的最大连接数,0和None表示不限制连接数
mincached=2, #初始化时,链接池中至少创建的空闲的链接,0表示不创建
maxcached=5, #链接池中最多闲置的链接,0和None不限制
maxshared=3, #链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
blocking=True, #连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
maxusage=None, #一个链接最多被重复使用的次数,None表示无限制
setsession=[], #开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
ping=0, #ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
host='127.0.0.1',
port=3306,
user='root',
password='root',
database='pooldb',
charset='utf8')deffunc():
conn=POOL.connection(shareable=False)
cursor=conn.cursor()
cursor.execute('select * from tb1')
result=cursor.fetchall()
cursor.close()
conn.close()
func()
二、SQLALchemy
1、简介
定义:SQLAlchemy是一个基于Python实现的ORM框架。提供了SQL工具包及对象关系映射(ORM)工具,该框架建立在 DB API之上,使用关系对象映射进行数据库操作。
本质:将类和对象转换成SQL,然后使用数据库API执行SQL并获取执行结果。
组成部分:
Engine 框架的引擎
Connection Pooling 数据库连接池
Dialect 选择连接数据库的DB API种类
Schema/Types 架构和类型 SQL Exprression Language,SQL表达式语言
注意:SQLAlchemy本身无法操作数据库,必须依赖pymysql等第三方插件,它不支持修改字段
2、简单使用(执行原生sql)
#-*-coding:utf-8 -*-
from sqlalchemy importcreate_engineimportsqlalchemyfrom sqlalchemy.engine.base importEngine#生成一个engine对象
engine=create_engine("mysql+pymysql://root:[email protected]:3306/flaskdb?charset=utf8",
max_overflow=0, #超过连接池大小外最多创建的连接
pool_size=5, #连接池大小
pool_timeout=30, #等待线程池中线程最多等待时间
pool_recycle=-1 #多久对线程池的线程进行重置
)#创建连接(执行原生sql)
conn=engine.raw_connection()#获取游标对象
cursor=conn.cursor()#数据库操作#创建表
cursor.execute('create table test3 (name char(32),age int)')#插入数据
cursor.execute('insert into test (name) value(1)')#删除表
cursor.execute('drop table test')
cursor.execute('show tables')
res=cursor.fetchall()print(res)
3、orm表创建和表关系
(1)创建表、删除表
#-*-coding:utf-8 -*-
importdatetimefrom sqlalchemy importcreate_enginefrom sqlalchemy.ext.declarative importdeclarative_base#导入字段和字段属性
from sqlalchemy importColumn,Integer,String,Text,ForeignKey,DateTime,UniqueConstraint,Index#创建一个基类
Base=declarative_base()#表模型类
classUser(Base):__tablename__='user' #表名
id=Column(Integer,primary_key=True) #设置为主键
name=Column(String(32),index=True,nullable=False) #不能为空,索引
email=Column(String(32),unique=True) #唯一
#注意:datetime.datetime.now不能加括号,加了括号,以后永远是当前时间,不会再改变
# datetime.now:插入数据的时间
# datetime.now(): 程序部署的时间,每条数据时间都是同样,且固定不变的 create_time=Column(DateTime,default=datetime.datetime.now)
extra=Column(Text,nullable=True)#__table_args__ 类似django的Meta
__table_args__=(
UniqueConstraint('id', 'name'