1、ORM介绍:

  • 1. ORM:Object Relationship Mapping
  • 2. 大白话:对象模型与数据库表的映射

2、将ORM模型映射到数据库中:

1. 用`declarative_base`根据`engine`创建一个ORM基类。


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

HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test_flask_learn'
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)


2. 用这个`Base`类作为基类来写自己的ORM类。要定义`__tablename__`类属性,来指定这个模型映射到数据库中的表名。

class Person(Base):
    __tablename__ = 'person'


3. 创建属性来映射到表中的字段,所有需要映射到表中的属性都应该为Column类型:

class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50))
    age = Column(Integer)
    country = Column(String(50))


4. 使用`Base.metadata.create_all()`来将模型映射到数据库中。
5. 一旦使用`Base.metadata.create_all()`将模型映射到数据库中后,即使改变了模型的字段,也不会重新映射了。

完整代码:

# encoding: utf-8

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

HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test_flask_learn'
USERNAME = 'root'
PASSWORD = 'zhoubeijing130'

# 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(50),age int)

# 1. 创建一个ORM模型,这个ORM模型必须继承自sqlalchemy给我们提供好的基类
class Person(Base):
    __tablename__ = 'person'
    # 2. 在这个ORM模型中创建一些属性,来跟表中的字段进行一一映射。这些属性必须是sqlalchemy给我们提供好的数据类型。
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50))
    age = Column(Integer)
    country = Column(String(50))


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

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐