SQLAlchemyの学習(A)

ウェッジ

SQL言語

SELECT                                                            
  a.uid,

    count( if (a.total_sell_balance>a.total_buy_balance,true,null)) / count(*) as num1, 
 
    count(*) as num2,  

    count( if (a.total_sell_balance > a.total_buy_balance,true,null)) as profitnum,

  CASE
        # 如果b.trade_days <= 20则显示b.trade_days
    WHEN b.trade_days <= 20 THEN b.trade_days
    WHEN b.trade_days > 20  THEN (b.trade_num / b.trade_days) * 20
  END as avgnum,

  b.trade_days as trade_days

FROM  tb_stat_win_rate as a 
LEFT JOIN tb_stat_month_trade as b on a.uid=b.uid

対応SQLAlchemyのORM

query = db.session.query(
            TbStatWinRate.uid,
            
            func.count(func.if_(TbStatWinRate.total_sell_balance > TbStatWinRate.total_buy_balance,True,None)) / func.count(TbStatWinRate.uid),

            func.count(TbStatWinRate.uid),
                                # 如果TbStatWinRate.total_sell_balance > TbStatWinRate.total_buy_balance,则显示True,否则显示None
            func.count(func.if_(TbStatWinRate.total_sell_balance > TbStatWinRate.total_buy_balance,True,None)),

            func.if_(TbStatMonthTrade.trade_days <= 20, TbStatMonthTrade.trade_days,(TbStatMonthTrade.trade_num / TbStatMonthTrade.trade_days) * 20),
    
            TbStatMonthTrade.trade_days, 
            
    ).outerjoin(TbStatWinRate,TbStatMonthTrade.uid == TbStatWinRate.uid,isouter=True)

セクションI:SQLAlchemyの説明:

1.SQLAlchemyは、Pythonプログラミング言語のORMフレームワークであり、フレームワークは、リレーショナルオブジェクトマッピングデータベース操作を使用して、データベースAPI上に構築され、短いである:SQLにオブジェクトを変換し、そのデータを使用し、SQLのAPIを実行します結果を得ることができます。

ここに画像を挿入説明
:それは、データベースの操作を可能にする、異なる呼プロファイル異なるデータベースAPIによれば、他のサードパーティ製プラグイン、APIおよびデータ交換のための方言をpymsqlなければならないので2.SQLAlchemy自体のような、データベースを操作することができません

MySQL-Python
    mysql+mysqldb://<username>:<password>@<host>/<dbname>:<port>[?<options>]
   
pymysql
    mysql+pymysql://<username>:<password>@<host>/<dbname>:<port>[?<options>]
      
cx_Oracle
    oracle+cx_oracle://<user>:<pass>@<host>:<port>/<dbname>[?key=value&key=value...]
   
更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html

注意:

  

データベーステーブルに書き込まれた文字は必要が文字セットをコーディング追加する= UTF8

engine = create_engine('mysql+pymysql://[email protected]:3306/db2?charset=utf8')  
#1 连接已存在的数据库

engine = create_engine('sqlite:///dbyuan67.db', echo=True)
#2 打印sql语言

セクションII:テーブルを作成します。

SQL言葉遣い

CREATE TABLE `person`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(20) NOT NULL,
    `age` INT NOT NULL DEFAULT 20,
    `sex` SMALLINT DEFAULT 1,
    `t_time` DATETIME NULL
) DEFAULT CHARSET='utf8';

SQL表現言語

# -*- coding: utf-8 -*-
# @Author: Lai

from sqlalchemy import (Table, MetaData, create_engine,
                        Column, Integer, String, SmallInteger, DateTime)
from datetime import datetime
from sqlalchemy.orm import mapper, sessionmaker

engine = create_engine("mysql+mysqldb://root:[email protected]/todo?charset=utf8")
metadata = MetaData()

# table
user = Table("user", metadata,
        Column("id", Integer, nullable=False, primary_key=True, autoincrement=True),
        Column("username", String(20), nullable=False),
        Column("age", Integer, nullable=False),
        Column("sex", SmallInteger, default=1),
        Column("create_time", DateTime, default=datetime.now)
    )

# model
class User(object):
    def __init__(self, username=None, age=None, sex=None):
        if username:
            self.username = username
        if age:
            self.age =age
        if sex:
            self.sex =sex

# table与model映射
mapper(User, user)


if __name__ == "__main__":
    # metadata.create_all(bind=engine)  #建表
    Session = sessionmaker(bind=engine)
    session = Session()

    try:
        user = User("rose", 20, 0)
        session.add(user)
        session.commit()
    except Exception as e:
        print(e)
        session.rollback()
    session.close()

SQLのORM

# -*- coding: utf-8 -*-
# @Author: Lai

from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (create_engine, Column, Integer, String, SmallInteger, DateTime)
from sqlalchemy.orm import Session

engine = create_engine("mysql+mysqldb://root:[email protected]/todo?charset=utf8")
Base = declarative_base()


class Human(Base):
    __tablename__ = "human"
    id = Column("id", Integer, autoincrement=True, primary_key=True)
    name = Column("name", String(20), nullable=False, unique=True)
    age = Column("age", Integer, nullable=False)
    sex = Column("sex", SmallInteger, default=1)
    create_time = Column("create_time", DateTime, default=datetime.now)

    def __repr__(self):
        return "name {}".format(self.name)


if __name__ == "__main__":
    # Base.metadata.create_all(bind=engine) # 建表
    session = Session(bind=engine)
    # h = Human(name="king001", age=30, sex=1)
    # session.add(h)
    
    # Human.__table__ ------------------------------>orm转经典类型(table类型)
    
    try:
        res = []
        for i in range(2,11):
            h = Human(name="king00{}".format(str(i)), age=i, sex=1)
            res.append(h)

        session.add_all(res)
        session.commit()
    except Exception as e:
        print(e)
        session.rollback()
    session.close()

セクションIII:反射テーブル

おすすめ

転載: www.cnblogs.com/lilied/p/11116686.html