sqlalchemy learning (a)

wedge

sql language

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

Corresponding 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)

Section I: sqlalchemy description:

1.SQLAlchemy is an ORM framework in the Python programming language, the framework is built on a database API, using relational object mapping database operation, in short is: convert objects into SQL, and then use the data and execute SQL API get the results.

Here Insert Picture Description
2.SQLAlchemy itself can not operate the database, since it must pymsql other third-party plug-ins, Dialect for API and data exchange, according to the different call profiles different database API, enabling operation of the database, such as:

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

note:

  

Characters written to the database table when the need to add coding charset = utf8

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

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

Section II: Create a table

sql wording

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 expression language

# -*- 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()

Section III: reflection table

Guess you like

Origin www.cnblogs.com/lilied/p/11116686.html