tormysql 使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangxiaodong88/article/details/86494125

创建连接池

https://pypi.org/project/TorMySQL/

import tornado.ioloop
from project_settings.db_settings import DBMysql

user = DBMysql[0]["user"]
host = DBMysql[0]["host"]
db = DBMysql[0]["db"]
password = DBMysql[0]["password"]
import tormysql
import pymysql.cursors

pool = tormysql.ConnectionPool(
    # max_connections=100,  # max open connections
    max_connections=500,  # max open connections
    idle_seconds=7500,  # conntion idle timeout time, 0 is not timeout
    wait_connection_timeout=600,  # wait connection timeout
    host=host,
    user=user,
    passwd=password,
    db=db,
    charset="utf8",
    cursorclass=pymysql.cursors.DictCursor # 获取的是字典形式, 没有这句获取的是元组
)

db_base

from yang_test.common.connect_pool import pool

from yang_test.common.base_model import BaseModel


# class DBBase(BaseModel):
class DBBase():
    def __init__(self, conn=None):
        self.conn = conn

    async def update_data(self, sql):
        """更新数据"""
        async with await pool.Connection() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(sql)
        return ""

    async def get_many(self, sql, n):
        """获取 多条数据"""
        async with await pool.Connection() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(sql)
                data = cursor.fetchmany(n)
        # return data
        return BaseModel.query(data)

    async def get_all(self, sql):
        """获取 所有数据"""
        async with await pool.Connection() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(sql)
                data = cursor.fetchall()
        return BaseModel.query(data)

    async def get_one(self, sql):
        """获取一条数据"""
        async with await pool.Connection() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute(sql)
                data = cursor.fetchone()
        return BaseModel.query(data)

    async def add_one(self, sql):
        """插入一条数据"""
        flag = True
        async with await pool.Connection() as conn:
            try:
                async with conn.cursor() as cursor:
                    await cursor.execute(sql)
            except Exception as e:
                await conn.rollback()
                flag = False
            else:
                await conn.commit()
        return flag

BaseModel 封装字典为 对象


class BaseModel(dict):
    _table_name = ''
    _optional_cols = []

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError as k:           
            if key in self._optional_cols:
                return ''
            else:
                raise AttributeError

    def __setattr__(self, key, value):
        self[key] = value

    @classmethod
    def get_model(cls, data):
        if not data or not len(data):
            return None
        if isinstance(data, list):
            models = [cls(d) for d in data]
            return models

        if isinstance(data, dict):
            return cls(data)
        return None

    @classmethod
    def query(cls, data):
        return cls.get_model(data)

    @classmethod
    def get_model_old(cls, data):
        if not data or not len(data):
            return None
        if isinstance(data, list):
            models = list()
            for d in data:
                m = cls(d)
                models.append(m)
            return models

        if isinstance(data, dict):
            return cls(data)
        return None

操作数据库 sql


from yang_test.db.db_base import DBBase

STATE_DEFAULT = 1


class member(DBBase):
    def __init__(self, conn=None):
       pass

    async def get_by_users(self, user_ids):
        data = dict()
        data["state"] = STATE_DEFAULT
        if not user_ids or (user_ids and len(user_ids) == 1):
            data["user_id"] = user_ids[0] if user_ids else ""
            sql = "SELECT user_id,college_id FROM member where state='{state}' and user_id = '{user_id}'"
        else:
            data["user_id"] = tuple(user_ids)
            sql = "SELECT user_id,college_id FROM member where state='{state}' and user_id in {user_id}"
        sql = sql.format(**data)
       
        one = await self.get_all(sql)
        return one

    async def get_one_by_user(self, user_id):
        data = dict()
        data["user_id"] = user_id
        data["state"] = STATE_DEFAULT
        sql = "SELECT * FROM member where user_id='{user_id}' and state='{state}' ORDER  BY created_at DESC"
        sql = sql.format(**data)
        one = await self.get_one(sql)
        return one

    async def update_state_by_college(self, college_id, state=0):
        """修改 动态的状态 默认修改为无效"""
        data = dict()
        data["college_id"] = college_id
        data["state"] = state
        sql = "UPDATE member SET state = '{state}'  where college_id='{college_id}'"
        sql = sql.format(**data)
        res = await self.update_data(sql)
        return True

猜你喜欢

转载自blog.csdn.net/yangxiaodong88/article/details/86494125
今日推荐