Mysql SqlAlchemy Basic Steps
1.SqlAlchemy Basic structure syntax is as follows:
Case:
From SQLAlchemy import create_engine,column,string,integer,foreignkeyfrom sqlalchemy.ext.declarative Import Declarative_basefrom sqlalchemy.orm import Sessionmaker,relationshipimport pymysqlengine = Create_engine ("mysql+ Pymysql://chen:[email protected]:3306/school ", encoding= ' Utf-8 ', echo=true) #echo屏幕输出信息session_class = Sessionmaker (bind=engine) #创建与数据库的会话session class, notice that this is a class that is returned to the session, not the instance base = Declarative_base () # Generate ORM Base class User (Base): __tablename__ = "users" #定义表名 id = Column (integer,primary_key=true) #设置ID主键自增长 name = Co Lumn (String), Nullable=false) #字符集长度class Address (Base): __tablename__ = ' address ' id = Column (integer,primary_key =true) address = column (String (), nullable=false) user_id = column (Integer,foreignkey (' users.id ')) #设置外键, Format table name. field user = relationship (' user ') Base.metadata.create_all (engine) #创建表结构session = Session_class () #生成session实例user_obj = User (name= "chenchangqing") #生成需要创建的数据对象session. Add (user_obj) #把要创建的数据对象添加到这个session里,A unified creation of Session.commit () #统一提交, creating data
6, Eighth week-network programming Advanced-SQLAlchemy ORM Framework application in Python language