See More

#!/bin/env python3 # -*- coding:utf-8 -*- # python中的数据库DB-API返回的数据结构 ''' [ ('1', 'Michael'), ('2', 'Bob'), ('3', 'Adam') ] ''' # 用class实例表示 # 把关系数据库的表结构映射到对象上,即Object-Relational Mapping # ORM框架 ''' class User(object): def __init__(self, id, name): self.id = id self.name = name [ User('1', 'Michael'), User('2', 'Bob'), User('3', 'Adam') ] ''' # python 中的ORM框架SQLAlchemy # # 导入: from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # 创建对象的基类: Base = declarative_base() # 定义User对象: class User(Base): # 表的名字: __tablename__ = 'user' # 表的结构: id = Column(String(20), primary_key=True) name = Column(String(20)) # 初始化数据库连接:str engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test') # 创建DBSession类型: DBSession = sessionmaker(bind=engine) # 有了ORM框架,添加记录可视为添加User对象 # DBSession对象可视为当前数据库连接 # 创建session对象: session = DBSession() # 创建新User对象: new_user = User(id='5', name='Bob') # 添加到session: session.add(new_user) # 提交即保存到数据库: session.commit() # 关闭session: session.close() # 查询User对象 # 创建Session: session = DBSession() # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行: user = session.query(User).filter(User.id=='5').one() # 打印类型和对象的name属性: print('type:', type(user)) print('name:', user.name) # 关闭Session: session.close() # 定义关系 class User(Base): __tablename__ = 'user' id = Column(String(20), primary_key=True) name = Column(String(20)) # 一对多: books = relationship('Book') class Book(Base): __tablename__ = 'book' id = Column(String(20), primary_key=True) name = Column(String(20)) # “多”的一方的book表是通过外键关联到user表的: user_id = Column(String(20), ForeignKey('user.id'))