1. use Declarative_base to create an ORM base class based on the engine.
2. Write your own ORM class using base class as the base class. To define the __tablename__ class property, specify the name of the table that the model maps to in the database.
3. create an attribute to map to a field in a table, all attributes that need to be mapped to a table should be of type column
4. use ' Base.metadata.create_all () ' to map the model to the database.
5. Once the model has been mapped to the database using ' Base.metadata.create_all () ', the field of the model is not remapped, even if it is changed
1 #Coding:utf-82 #Author:liangjun.3 4 fromSQLAlchemyImportCreate_engine, Column, Integer, String5 fromSqlalchemy.ext.declarativeImportDeclarative_base6 7HOSTNAME ='127.0.0.1'8PORT = 33069DATABASE ='Sqlalchemy_first'TenUSERNAME ='Root' OnePASSWORD ='123456' A -Db_uri ='Mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?charset=utf8'. Format ( -Username=username, Password=password, Host=hostname, Port=port, dbname=DATABASE the ) -Engine =create_engine (Db_uri) -Base =declarative_base (Engine) - + - #Creating an ORM model + classPerson (Base): A __tablename__=' Person' atid = Column (Integer, Primary_key=true, autoincrement=True) -Name = Column (String (length=50)) -Age =Column (Integer) - - #model Map to database -Base.metadata.create_all ()
"Flask" ORM model creation and database mapping