SQLALchemy
sqlalchemy安装
pip install sqlalchemy
mysqldb是Python支持的MySQL数据库驱动
· pip install mysqlclient(Windows) · pip install mysql-python(mix os) · apt-get install python-mysqldb(Linux Ubuntu)
提示:ModuleNotFoundError: No module named 'MySQLdb' 安装以上
数据库配置信息
'数据库类型+数据库驱动名称://用户名:密码@服务器地址:端口号/数据库名'
如:
mysql+mysqldb: //root:@localhost:3306/Students?charset=utf8
核心类介绍
from sqlalchemy import Column, ForeignKey, Integer, String # ORM中对象映射中与数据库中对应的数据类型 from sqlalchemy.ext.declarative import declarative_base # 所有定义的类 需要基础的基类 from sqlalchemy.orm import relationship # 表与表之间的关系定义 from sqlalchemy import create_engine # 创建数据库之间的链接 from sqlalchemy.orm import sessionmaker # 操作数据库之间的会话
对于数据类型可以在 # sqlalchemy/__init__.py 去查看
from .types import BLOB from .types import Boolean from .types import CHAR from .types import CLOB from .types import Date from .types import DateTime from .types import DECIMAL from .types import Float from .types import INTEGER from .types import JSON from .types import LargeBinary from .types import NCHAR from .types import Numeric from .types import NVARCHAR from .types import REAL from .types import SMALLINT from .types import SmallInteger from .types import String from .types import TEXT
远远不止这些,并且 提供了多种命名方式
基本建表流程
# coding = utf-8 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String mysql_sql = "mysql+mysqldb://root:root@localhost:3306/blog?charset=utf8" # 这里建立一个Person table engine = create_engine(mysql_sql) Base = declarative_base() class Person(Base): __tablename__ = 'Person' id = Column(Integer, primary_key=True) name = Column(String(25), nullable=False) # 创建库 Base.metadata.create_all(engine)
一对多关系
一对多关系
class User(Base): __tablename__ = "User" id = Column(Integer, primary_key=True) username = Column(String(64), nullable=False, index=True) password = Column(String(64), nullable=False) email = Column(String(64), nullable=False, index=True) articles = relationship("Article") def __repr__(self): return '%s' % self.__class__.__name__ class Article(Base): __tablename__ = 'Article' id = Column(Integer, primary_key=True) title = Column(String(255), nullable=False, index=True) content = Column(Text) user_id = Column(Integer, ForeignKey('User.id')) user = relationship('User') def __repr__(self): return '%s' % self.__class__.__name__
- nullable 是否允许字段为null ,False
- index :是否建立索引
- relationship 只是维护关系,表中并无体现实际字段 ,内容相互关联的表
- ForeignKey: 为定义外键,内容为相互关联的外键字段,注意与__tablename__中内容相符合
一对一关系
一对一关系
一个用户User有唯一的扩展信息。我们可以把它们放到另一张 UserInfo 表中,关系是一对一
backref: 可以单边维护关系,两边不需要同时写relationship
class UserInfo(Base): __tablename__ = 'userinfo' id = Column(Integer, primary_key=True) name = Column(String(64)) qq = Column(String(11)) phone = Column(String(11)) link = Column(String(64)) user_id = Column(Integer, ForeignKey('User.id')) class User(Base): __tablename__ = "User" id = Column(Integer, primary_key=True) username = Column(String(64), nullable=False, index=True) password = Column(String(64), nullable=False) email = Column(String(64), nullable=False, index=True) articles = relationship("Article") articles = relationship("UserInfo",backref=False,uselist=False) def __repr__(self): return '%s' % self.__class__.__name__
多对多关系
多对多关系
标签与博客之间就是一个多对多的关系,需要引入第三张表来存放,两则之间的关系。
# 为中间表 article_tag = Table( 'article_tag', Base.metadata, Column('article_id', Integer, ForeignKey('Article.id')), Column('tag_id', Integer, ForeignKey('Tag.id')) ) class Tag(Base): __tablename__ = 'Tag' id = Column(Integer, primary_key=True) name = Column(String(64), nullable=False, index=True) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.name)
基本操作s
# coding = utf-8 # coding = utf-8 from sqlalchemy import create_engine, ForeignKey, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Text, Float, Date, DateTime from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker mysql_sql = "mysql+mysqldb://root:root@localhost:3306/test?charset=utf8" engine = create_engine(mysql_sql) Base = declarative_base() class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String(25)) Price = Column(Integer) def __repr__(self): return "%s %s %s %s"% (self.__class__.__name__,self.Id,self.Name,self.Price) Base.metadata.bind = engine Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # 插入数据 # session.add_all( # [Car(Id=1, Name='Audi', Price=52642), # Car(Id=2, Name='Mercedes', Price=57127), # Car(Id=3, Name='Skoda', Price=9000), # Car(Id=4, Name='Volvo', Price=29000), # Car(Id=5, Name='Bentley', Price=350000), # Car(Id=6, Name='Citroen', Price=21000), # Car(Id=7, Name='Hummer', Price=41400), # Car(Id=8, Name='Volkswagen', Price=21600)]) # session.commit() # 查询所有 rs = session.query(Car).all() for x in rs: print(x) # 查询第一次数据数据 rs1 = session.query(Car).get(1) print(rs1) # 增加一个数据 c1 = Car(Name="dongfeng",Price="255000") session.add(c1) session.commit() # 过滤数据 条件查询 谓词 c2 = session.query(Car).filter(Car.Name.like("V%")) print(c2) # 查看Sql print(c2.all()) # 删除 c3 = session.query(Car).filter(Car.Id.in_([1])) print("c3:%s",c3) session.delete(c3)