mysql自建api

核心代码

import pymysql

from game_store_service.config import Config


class Store:
    def __init__(self):
        host = Config.DATA_MYSQL_HOST
        port = Config.DATA_MYSQL_PORT
        user = Config.DATA_MYSQL_USER
        pwd = Config.DATA_MYSQL_PWD
        db_name = Config.DATA_MYSQL_DB_NAME
        self.con = pymysql.connect(host=host, port=port, user=user, password=pwd, db=db_name)

    def insert_data(self, table, fields, d):
        sql = f'insert into {table} ({",".join(fields)}) values ({",".join(["%s" for i in fields])})'
        with self.con.cursor() as cursor:
            cursor.executemany(sql, d)
        self.con.commit()
        print('insert success!')

    def update_data(self, table, fields, str_fields, data, where_field, where_val):
        # 判断更新活动时间是否为空 如果为空 取消更新
        fields = fields[:]
        items = ''
        for index, i in enumerate(fields):
            if i in str_fields:
                items += f' {i}="{data[index]}"'
            else:
                items += f' {i}={data[index]}'
            if index < len(fields) - 1:
                items += ','
        sql = f'update {table} set{items} where {where_field}="{where_val}"'
        with self.con.cursor() as cursor:
            cursor.execute(sql)
        self.con.commit()
        print('update success!')

    def query_data_by_field(self, table, field, val):
        sql = f'select * from {table} where {field}="{val}"'
        with self.con.cursor() as cursor:
            cursor.execute(sql)
        d = cursor.fetchone()
        return d

    def query_data_by_game_id_order_by_add_time_desc(self, table, field, val):
        sql = f'select * from {table} where {field}="{val}" order by add_time desc'
        with self.con.cursor() as cursor:
            cursor.execute(sql)
        d = cursor.fetchone()
        return d

    def query_many_filter(self, table, fields, data):
        if len(data) != len(fields):
            return 'len not equal'
        filters = ""
        for index, i in enumerate(fields):
            filters += f' {i}="{data[index]} "'
            if index < len(fields) - 1:
                filters += 'and'

        sql = f'select * from {table} where{filters}'
        with self.con.cursor() as cursor:
            cursor.execute(sql)
        d = cursor.fetchone()
        return d


if __name__ == '__main__':
    s = Store()

你可能感兴趣的:(mysql自建api)