暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

mysql&python 动态 统计年/月/日数据

codefan 2019-01-22
201

根据某字段动态统计年/月/日数据

依赖的包

Click==7.0 PyMySQL==0.9.3

数据示例

kprqvalue
2017-01-01 10:12:4210
2018-12-01 12:12:1220
2018-12-01 15:14:1245
2018-12-01 14:12:5234
2018-12-01 14:17:2245
2018-12-01 14:19:2234
2018-12-01 14:52:5233
2018-12-03 14:12:5234
2018-12-04 14:17:2245
2018-12-06 14:19:2234
2018-12-06 14:52:5233

config.json

  1. {

  2.  "test": {

  3.    "mysql": {

  4.      "host": "192.168.7.2",

  5.      "user": "root",

  6.      "password": "password",

  7.      "db": "tests",

  8.      "port": 3310,

  9.      "charset": "utf8"

  10.    }

  11.  },

  12.  "prd": {

  13.    "mysql": {

  14.      "host": "localhost",

  15.      "user": "root",

  16.      "password": "password",

  17.      "db": "tests",

  18.      "port": 3306,

  19.      "charset": "utf8"

  20.    }

  21.  }

  22. }

代码

  1. import json,pymysql,click


  2. class Count(object):


  3.    base_sql = """

  4. select {select},sum(value) as sum_value

  5. from tests

  6. group by {select}

  7. """

  8.    def __init__(self,config):

  9.        self.mysql_config = config

  10.        self.conn = pymysql.connect(**self.mysql_config)

  11.        self.cursor = self.conn.cursor()


  12.    def _execute(self,sql,*args):

  13.        self.cursor.execute(sql,*args)

  14.        datas  = self.cursor.fetchall()

  15.        self.cursor.close()

  16.        self.conn.close()

  17.        return datas



  18.    @classmethod

  19.    def from_settings(cls,config):

  20.        return cls(config)



  21.    def get_year(self):

  22.        select = 'substr(kprq,1,4)'

  23.        sql = self.base_sql.format(select=select)

  24.        return self._execute(sql)


  25.    def get_month(self):

  26.        select = 'substr(kprq,1,7)'

  27.        sql = self.base_sql.format(select=select)

  28.        return self._execute(sql)


  29.    def get_day(self):

  30.        select = 'substr(kprq,1,10)'

  31.        sql = self.base_sql.format(select=select)

  32.        return self._execute(sql)



  33.    @classmethod

  34.    def run(cls,config):

  35.        for arg in ('year','month','day'):

  36.            attr = 'get_' + arg

  37.            data = getattr(cls.from_settings(config),attr)()

  38.            print('attr:{}---data:{}'.format(attr,data))


  39. @click.command()

  40. @click.option('--mode', help='local/test/prd')

  41. def main(mode):

  42.    with open('config.json','r',encoding='utf-8') as fr:

  43.        config = json.load(fr)[mode]['mysql']

  44.        Count.run(config)

  45. if __name__ == '__main__':

  46.    main()


文章转载自codefan,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论