一、数据库创建表格
from sqlalchemy import create_engine # 导入引擎 from sqlalchemy import Column,Integer,CHAR # 导入数据库基本模块 from sqlalchemy.ext.declarative import declarative_base # 导入基类 link = "mysql+pymysql://root:123456@localhost:3306/aaa?charset=utf8" engine = create_engine(link) # 创建数据库引擎 Base = declarative_base() class Teacher(Base): __tablename__ = 'teacher' # 数据表名字 id = Column(Integer,primary_key=True,nullable=False) # id 字段 name = Column(CHAR(20),nullable=False) # name 字段 Base.metadata.create_all(bind=engine)
二、数据库追加内容
from sqlalchemy import create_engine from sqlalchemy import Column,Integer,CHAR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 导入会话 link = "mysql+pymysql://root:123456@localhost:3306/aaa?charset=utf8" engine = create_engine(link) Session = sessionmaker(bind=engine) # 创建会话类 session = Session() # 实例化会话 Base = declarative_base() class Books(Base): __tablename__ = 'book' 编号 = Column(Integer,primary_key=True,nullable=False) 书名 = Column(CHAR(20),nullable=False) 作者 = Column(CHAR(20), nullable=False) 价格 = Column(CHAR(20), nullable=False) 出版社 = Column(CHAR(20), nullable=False) 数量 = Column(CHAR(20), nullable=False) def Add_info(self): add_info = Books(编号=1,书名="计算机基础教程",作者="吴昊",价格=35,出版社="北京邮电出版社",数量=8) session.add(add_info) # 添加会话 session.commit() # 提交会话,执行到数据库 session.close() # 关闭会话 if __name__ == '__main__': books = Books() books.Add_info() # Base.metadata.create_all(bind=engine)