知乎: sqlalchemy 的 ORM 与 Core 混合方式操作数据库是一种怎样的体验?
答: 酸!
本文基于:win 10 + python 3.4 + sqlalchemy 1.0.13
基本步骤如下:
1. 绑定数据库
from sqlalchemy import create_engine engine = create_engine(‘sqlite:///:memory:‘,echo = True)
2. 建立会话
from sqlalchemy.orm import Session session = Session(engine)
3. 元数据
from sqlalchemy import MetaData metadata = MetaData(engine)
4. 定义表
from sqlalchemy import Table, Column, Integer, String, ForeignKey users_table = Table(‘users‘, metadata, Column(‘id‘, Integer, primary_key = True), Column(‘name‘, String), Column(‘fullname‘, String), Column(‘password‘, String) )
5. 创建表
# metadata.create_all() # 方式一 users_table.create() # 方式二
6. 定义类
class User(object): def __init__(self,name,fullname,password): self.name = name self.fullname = fullname self.password = password def __repr__(self): return "<User(‘%s‘,‘%s‘,‘%s‘)>" % (self.name, self.fullname, self.password)
7. 映射类、表
from sqlalchemy.orm import mapper mapper(User, users_table)
8. 然后,就可以使用会话对数据库进行操作
session.add(User(‘ed‘,‘Ed Jones‘,‘edspassword‘)) session.commit()
9. 完整代码
# 绑定数据库 from sqlalchemy import create_engine engine = create_engine(‘sqlite:///:memory:‘,echo = True) # 建立会话 from sqlalchemy.orm import Session session = Session(engine) # 元数据 from sqlalchemy import MetaData metadata = MetaData(engine) # 定义表 from sqlalchemy import Table, Column, Integer, String, ForeignKey users_table = Table(‘users‘, metadata, Column(‘id‘, Integer, primary_key = True), Column(‘name‘, String), Column(‘fullname‘, String), Column(‘password‘, String) ) # 创建表 # metadata.create_all() # 方式一 users_table.create() # 方式二 # 定义类 class User(object): def __init__(self,name,fullname,password): self.name = name self.fullname = fullname self.password = password def __repr__(self): return "<User(‘%s‘,‘%s‘,‘%s‘)>" % (self.name, self.fullname, self.password) # 映射类、表 from sqlalchemy.orm import mapper mapper(User, users_table) # 然后,就可以使用会话对数据库进行操作 session.add(User(‘ed‘,‘Ed Jones‘,‘edspassword‘)) session.commit()
时间: 2024-09-30 11:20:24