SQLAlchemy:
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
结构:
SQLAlchemy本身无法操作数据库,其必须以pymysql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:
ORM功能使用:
1,创建表:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from sqlalchemy.ext.declarative import declarative_base 4 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index 5 from sqlalchemy.orm import sessionmaker, relationship 6 from sqlalchemy import create_engine 7 #jdbc:mysql://localhost:3306 8 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/s4day62db?charset=utf8", max_overflow=5) 9 10 Base = declarative_base() 11 12 13 # 创建单表 14 class Users(Base): 15 __tablename__ = 'users' 16 id = Column(Integer, primary_key=True) 17 name = Column(String(32)) 18 extra = Column(String(16)) 19 20 21 def init_db(): 22 Base.metadata.create_all(engine) 23 24 25 def drop_db(): 26 Base.metadata.drop_all(engine) 27 28 init_db() 29 30 #删除表 31 # drop_db()
运行结果:在mysql数据库创建了表单(注:运行代码之前要先在mysql数据库中建立数据库s4day62db)
2,创建两个表,这两个表之间有约束关系:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from sqlalchemy.ext.declarative import declarative_base 4 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index 5 from sqlalchemy.orm import sessionmaker, relationship 6 from sqlalchemy import create_engine 7 8 # jdbc:mysql://localhost:3306 9 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/s4day62db?charset=utf8", max_overflow=5) 10 11 Base = declarative_base() 12 13 14 #创建单表 15 class UserType(Base): 16 __tablename__ = 'users' 17 id = Column(Integer, primary_key=True, autoincrement=True) 18 title = Column(String(32), nullable=True, default='sf', index=True) 19 20 21 22 # 创建单表 23 class Users(Base): 24 __tablename__ = 'users' 25 id = Column(Integer, primary_key=True, autoincrement=True) 26 name = Column(String(32), nullable=True, default='sf', index=True) 27 email = Column(String(16), unique=True) 28 #添加约束 29 user_type_id = Column(Integer,ForeignKey("usertype.id")) 30 31 # __table_args__ = ( 32 # UniqueConstraint('id', 'name', name='uix_id_name'), 33 # Index('ix_n_ex', 'name', 'extra'), 34 # ) 35 36 37 def init_db(): 38 Base.metadata.create_all(engine) 39 40 41 def drop_db(): 42 Base.metadata.drop_all(engine) 43 44 45 init_db() 46 47 # 删除表 48 # drop_db()