标签:
知乎: sqlalchemy 的 ORM 与 Core 混合方式操作数据库是一种怎样的体验?
答: 酸!
本文基于:win 10 + python 3.4 + sqlalchemy 1.0.13
基本步骤如下:
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()
# 绑定数据库 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()
sqlalchemy 的 ORM 与 Core 混合方式使用示例
标签:
原文地址:http://www.cnblogs.com/hhh5460/p/5514459.html