ORM框架:AQLAlchemy
-作用:
1、提供简单的规则
2、自动转换成SQL语句
-DB first: 手动创建数据库以及表 -> ORM框架 -> 自动生成类
code first:手动创建类 ->ORM框架 -> 以及表
功能:
-创建数据库表
连接数据库(非SQLAlchemy,是pymsql)
类转换SQL语句
-操作数据行
增
删
改
查
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine Base = declarative_base() # 创建单表 class UserType(Base): __tablename__ = 'usertype' id = Column(Integer, primary_key=True,autoincrement=True) name = Column(String(32),nullable=True,default='sf',index=True) class Users(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True,autoincrement=True) name = Column(String(32),nullable=True,default='sf',index=True) extra = Column(String(16),unique=True) user_type_id = Column(Integer,ForeignKey('usertype.id')) def create_db(): engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) Base.metadata.create_all(engine) def delete_db(): engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) Base.metadata.drop_all(engine)
#增加 obj1 = UserType(name='普通用户') session.add(obj1) session.commit()
# obj1 = UserType(name='普通用户') objs=[ UserType(name='超级用户'), UserType(name='白金用户'), UserType(name='黑金用户') ] # session.add(obj1) session.add_all(objs) session.commit() session.close()
#修改 # session.query(UserType.id,UserType.name).filter(UserType.id>0).update({'name':'黑金'}) session.query(UserType.id,UserType.name).filter(UserType.id>2).update({UserType.name: UserType.name + "xxx"}, synchronize_session=False) session.commit() session.close()
# 删 # session.query(UserType.id,UserType.name).filter(UserType.id>3).delete()
# 查 # user_type_list = session.query(UserType).all() # for row in user_type_list: # print(row.id,row.name) # user_type_list = session.query(UserType.id,UserType.name).filter(UserType.id>2) # for row in user_type_list: # print(row.id,row.name)