sqlalchemy映射数据库

Posted python成长中

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlalchemy映射数据库相关的知识,希望对你有一定的参考价值。

from sqlalchemy import create_engine,Column,Integer,String
from sqlalchemy.ext.declarative import declarative_base

HOSTNAME = \'127.0.0.1\'

PORT = 3306

DATABASE = \'first_sqlalchemy\'

USERNAME = \'root\'

PASSWORD = \'123456\'

#dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" \\
         "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)


engine = create_engine(DB_URI)

Base = declarative_base(engine)

# create table person(id int primary key autoincrement, name varchar(32) unique,age smallint unsigende)

#1.创建一个ORM模型,这个orm模型必须继承sqlalchemy给提供我们的基类


class Person(Base):
    __tablename__ = \'person\'

#2.在这个ORM模型中创建一些属性,来跟表中的字段进行一一映射。这些属性必须是
#sqlalchemy给我们提供好的数据类型
    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(32))
    age = Column(Integer)

#3.将创建好的ORM模型,映射到数据中。
Base.metadata.create_all()

 

以上是关于sqlalchemy映射数据库的主要内容,如果未能解决你的问题,请参考以下文章

SQLAlchemy - 从自动加载表的内部连接映射列的子集

SQLAlchemy(一):SQLAlchemy去连接数据库ORM介绍将ORM模型映射到数据库中

flask 中orm关系映射 sqlalchemy的查询

石墨烯突变未映射 SQLAlchemy 中的模型

sqlalchemy映射数据库

SQLAlchemy外键的使用