一、简介
SQLAlchemy是一个基于Python实现的ORM框架。该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数据API执行SQL并获取执行结果
数据库的连接方式:
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...] sqlite sqlite:///test_s1.db
以pymysql为例:
create_engine(
"mysql+pymysql://root:123@127.0.0.1:3306/t1?charset=utf8"
,
max_overflow
=
0
,
# 超过连接池大小外最多创建的连接
pool_size
=
5
,
# 连接池大小
pool_timeout
=
30
,
# 池中没有线程最多等待的时间,否则报错
pool_recycle
=
-
1
# 多久之后对线程池中的线程进行一次连接的回收(重置)
)
二、实战
1、创建表, users和depart
# -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, String, Integer, ForeignKey engine = create_engine("sqlite:///test_s1.db") # 创建表 Base = declarative_base() class Depart(Base): __tablename__ = 'depart' id = Column(Integer, primary_key=True) title = Column(String(32), index=True, nullable=False) class Users(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) depart_id = Column(Integer, ForeignKey('depart.id')) def create_all(): Base.metadata.create_all(engine) def drop_all(): Base.metadata.drop_all(engine) if __name__ == '__main__': # 创建所有表 create_all() # 删除表 # drop_all()
标签:原生,__,sqlalchemy,Column,create,pymysql,engine,Base From: https://www.cnblogs.com/kongzhagen/p/16885971.html