SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
#创建表 def create_db(): engine = create_engine =(‘mysql+pymysql://root:741741@localhost:3306/db1‘,max_overflow = 5) Base.metadata.create_all(engine) #删除表 def drop_db() engine = create_engine =(‘mysql+pymysql://root:741741@localhost:3306/db1‘,max_overflow = 5) Base.metadata.drop_all(engine)
#!/usr/bin/env python # -*- coding:utf-8 -*- 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 engine = create_engine("mysql+pymysql://root:741741@localhost/db1",max_overflow = 5) Base = declarative_base() #创建单表 class UserType(Base): __tablename__ = ‘usertype‘ id = Column(Integer,primary_key = True,autoincrement = True) title = Column(String(32),nullable = True,index = True) class Users(Base): __tablename__ = ‘users‘ id = Column(Integer.primary_key = True,autoincrement = True,nullable=True) name = Column(String(32),nullable=True) extra = Column(string(16)) user_type_id = Column(Integer,ForeignKey(‘usertype,id‘)) __table_args__( UniqueConstraint(‘id‘,‘name‘,name = ‘uix_id_name‘) Index (‘ix_id_name‘,‘name‘,‘extra‘) )
原文:https://www.cnblogs.com/zhangj0918/p/10547343.html