zoukankan      html  css  js  c++  java
  • SQLAlchemy

    SQLAlchemy

    SQLAlchemy是一个基于Python实现的ORM框架。该框架建立在 DB API之上,使用关系对象映射进行数据库操作,也就是:将类和对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
    
    pip3 install sqlalchemy
    

    组成部分:

    Engine,框架的引擎
    Connection Pooling ,数据库连接池
    Dialect,选择连接数据库的DB API种类
    Schema/Types,架构和类型
    SQL Exprression Language,SQL表达式语言
    

    Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作

    MySQL-Python
        mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
    
    pymysql
        mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
    
    MySQL-Connector
        mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
    
    cx_Oracle
        oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
    

    例如:

    'mysql://root:@localhost:3306/mysqltest?charset=utf8'  --- 指定字符编码
    
    SQLALCHEMY_DATABASE_URI = 'mysql://root:@127.0.0.1:3306/dbname'
    

    创建表:(如何创建联合唯一)

    import datetime
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
    from sqlalchemy.orm import relationship
    
    Base = declarative_base()
    
    
    # ##################### 单表示例 #########################
    class Users(Base):
        __tablename__ = 'users'
    
        id = Column(Integer, primary_key=True)
        name = Column(String(32), index=True)
        age = Column(Integer, default=18)
        email = Column(String(32), unique=True)
        ctime = Column(DateTime, default=datetime.datetime.now)
        extra = Column(Text, nullable=True)
    
    
            # 类似于django 中的 class meta
    
            # 指定表的其他属性,联合主键,联合索引等等
    
        __table_args__ = (
            # UniqueConstraint('id', 'name', name='uix_id_name'),
            # Index('ix_id_name', 'name', 'extra'),
        )
    
    
    class Hosts(Base):
        __tablename__ = 'hosts'
    
        id = Column(Integer, primary_key=True)
        name = Column(String(32), index=True)
        ctime = Column(DateTime, default=datetime.datetime.now)
    
    
    # ##################### 一对多示例 #########################
    class Hobby(Base):
        __tablename__ = 'hobby'
        id = Column(Integer, primary_key=True)
        caption = Column(String(50), default='篮球')
    
    
    class Person(Base):
        __tablename__ = 'person'
        nid = Column(Integer, primary_key=True)
        name = Column(String(32), index=True, nullable=True)
        hobby_id = Column(Integer, ForeignKey("hobby.id"))
    
        # 与生成表结构无关,仅用于查询方便
        hobby = relationship("Hobby", backref='pers')
    
    
    # ##################### 多对多示例 #########################
    
    class Server2Group(Base):
        __tablename__ = 'server2group'
        id = Column(Integer, primary_key=True, autoincrement=True)
        server_id = Column(Integer, ForeignKey('server.id'))
        group_id = Column(Integer, ForeignKey('group.id'))
    
    
    class Group(Base):
        __tablename__ = 'group'
        id = Column(Integer, primary_key=True)
        name = Column(String(64), unique=True, nullable=False)
    
        # 与生成表结构无关,仅用于查询方便
        servers = relationship('Server', secondary='server2group', backref='groups')
    
    
    class Server(Base):
        __tablename__ = 'server'
    
        id = Column(Integer, primary_key=True, autoincrement=True)
        hostname = Column(String(64), unique=True, nullable=False)
    
    
    def init_db():
        """
        根据类创建数据库表
        :return: 
        """
        engine = create_engine(
            "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,  # 连接池大小
            pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
    
        Base.metadata.create_all(engine)
    
    
    def drop_db():
        """
        根据类删除数据库表
        :return: 
        """
        engine = create_engine(
            "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,  # 连接池大小
            pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
    
        Base.metadata.drop_all(engine)
    
    
    if __name__ == '__main__':
        drop_db()
        init_db()
    

    flask_sqlalchemy的使用:

    app/init

    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy(app)
    

    models

    from app import db
    
    
    class Comment(db.Model):
        __tablename__ = 'comment'
        id = db.Column(db.Integer,primary_key=True)
        content = db.Column(db.Text)
        movie_id = db.Column(db.Integer,db.ForeignKey('movie.id'))
        user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
        addtime = db.Column(db.DateTime,index=True,default=datetime.datetime.utcnow)
    
        def __repr__(self):
            return "<Comment %r>"%self.id
    
        def get_user(self):
            user = User.query.get_or_404(self.user_id)
            return user
    
        def get_movie(self):
            return Movie.query.get_or_404(self.movie_id)
    

    views

    # 1  修改密码
    
            user = User.query.filter_by(name=session['user']).first()
            user.pwd = generate_password_hash(data['repwd'])
    
            db.session.add(user)
            db.session.commit()         # 提交修改
    
     # 2 添加用户
    
        data = register_form.data
        user = User(
            name = data['name'],
            email = data['email'],
            mobile = data['mobile'],
            pwd = generate_password_hash(data['pwd']),
            uuid = uuid4().hex
        )
        db.session.add(user)
        db.session.commit()
    
        # 3 查询
    
        user = User.query.filter_by(name=session['user']).first_or_404()
    
        moviecol_data = MovieCol.query.join(Movie).filter(Movie.id == MovieCol.movie_id,
                MovieCol.user_id == user.id).order_by(MovieCol.addtime.desc()).paginate(page=page,per_page=5)
    
        # 4 删除
    
            tag = Tag.query.filter_by(id=id).first_or_404()
            db.session.delete(tag)
            db.session.commit()
    

    r

    补充

    如何批量插入大批数据?

    		可以使用非 ORM 的方式:
    
    
    		session.execute(
    		    User.__table__.insert(),
    		    [{'name': `randint(1, 100)`,'age': randint(1, 100)} for i in xrange(10000)]
    		)
    		session.commit()
    

    如何指定使用 InnoDB,以及使用 UTF-8 编码?

    		最简单的方式就是修改数据库的默认配置。如果非要在代码里指定的话,可以这样:
    
    
    		class User(BaseModel):
    		    __table_args__ = {
    		        'mysql_engine': 'InnoDB',
    		        'mysql_charset': 'utf8'
    		    }
    

    http://www.cnblogs.com/wupeiqi/articles/8259356.html

  • 相关阅读:
    System.IO.MemoryStream.cs
    System.IO.Stream.cs
    System.Web.HttpContext.cs
    System.Text.Encoding.cs
    System.Web.HttpRuntime.cs
    System.Web.Caching.Cache.cs
    System.Diagnostics.Stopwatch.cs
    FrameBuffer
    Java实现 洛谷 P1422 小玉家的电费
    Java实现 洛谷 P1422 小玉家的电费
  • 原文地址:https://www.cnblogs.com/big-handsome-guy/p/8591325.html
Copyright © 2011-2022 走看看