数据库查询转excel小工具

因业务需求需要经常从数据库拉数据生成excel

每次都从数据库软件中操作贼烦 

 于是自己随便写了一个 

有需要得拿去用吧

import psycopg2
import psycopg2.pool
import xlsxwriter

class Sql:
    '''
    database:库名
    user:用户名
    password:密码
    host:地址
    port:端口
    '''
    def __init__(self,database,user,password,host,port):
        self.database=database
        self.user=user
        self.password=password
        self.host=host
        self.port=port
    def _sql(self):
        self.conn = psycopg2.connect(database=self.database, user=self.user,
                                     password=self.password,host=self.host, port=self.port)
        self.cursor = self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()


    def select(self,sql,args=None):
        self._sql()
        #查询语句
        try:
            self.cursor.execute(sql,args)
            coloumns = [row[0] for row in self.cursor.description]
            result = [[str(item) for item in row] for row in self.cursor.fetchall()]
            return [dict(zip(coloumns, row)) for row in result],coloumns
        except Exception as ex:
            print(ex)
        finally:
            self.close()

    def execute(self,sql,args=None):
        ###修改提交语句
        self._sql()
        try:
            self.cursor.execute(sql,args)
            self.conn.commit()
            res=self.cursor.rowcount
            return res
        except Exception as x:
            print(x)
        finally:
            self.close()




def run(title,field,wbk,data,sheet_name):

    sheet1 = wbk.add_worksheet(sheet_name)
    get_excel(sheet1, title, data, field)


def get_excel(sheet,cov,res,rov):
    row=1
    sheet.write_row('A1', cov)
    for line in res:
        l=[]
        for i in range(len(rov)):
             l.append(line[rov[i]])
        sheet.write_row(row, 0, l)
        row += 1

if __name__ == '__main__':
    wbk = xlsxwriter.Workbook('weibo.xlsx')####生成excel对象
    sql = Sql("uniqlo_reviews_analytics","bigodata","B1g0uniqlo","117.50.14.201","22432")###生成Sql类
    post_data , columns = sql.select('''select * from stagingdata.posts WHERE createrdtime::date BETWEEN '{0}'::date and '{1}'::date 
                  '''.format('2019-05-01','2019-05-31'))####返回数据集  和所有字段集
    title=['帖子id','发帖人','微博内容','发帖时间','评论数','转发数','点赞数']#标题名 也可以传columns
    field=['posterid','postername','weibo','createrdtime','hnum','forward','aproval']#字段名  也可以传columns
    
    reply_data, columns = sql.select('''select * from stagingdata.reply t1 WHERE  EXISTS 
                  (select 0 from stagingdata.posts WHERE createrdtime::date BETWEEN '{0}'::date and '{1}' and 
                t1.posterid=posterid)
                      '''.format('2019-05-01', '2019-05-31'))  ####返回数据集  和所有字段集
    title1 = ['评论id', '评论内容', '评论时间','帖子id']  # 标题名 也可以传columns
    field1 = ['commentid', 'comment_text', 'comment_time',  'posterid']  # 字段名  也可以传columns

    run(title,field,wbk,post_data,'帖子')
    run(title1, field1, wbk, reply_data,'评论')
    wbk.close()

在很大程度上,python更注重可读性、一致性和软件质量,python的设计致力于可读性,带来了比其他语言更优秀的可重用性和可维护性,python秉承了一种独特的简洁和高可读性的语法,以及一种高度一致的编程序模式。

相对于C、C++、Java等编辑/静态类型语言,python的开发效率提升了3-5倍,也就是说代码量是其他编程语言的1/5-1/3,而且无需编译、链接步骤,提高程序员效率

绝大多数python程序能不做任何修改即可在所有主流计算机平台上运行,此外,python提供多种可选的独立程序,如用户图形界面、数据库接入、基于web系统、还提供了操作系统接口等。

python内置了众多预编译并可移植的功能模块,涵盖了从字符模式到网络编程等一系列应用级编程任务;此外,python可通过自行开发的库和众多的第三方库简化编程,第三方库包括网站开发、数值计算、串口编写、游戏开发等各个应用场景。

python脚本通过灵活的集成机制轻松的与应用程序的其他部分进行通信,这种集成使得python成为产品定制和扩展的工具,如今,python程序可以与C、C++相互调用,可以与java组件集成,与COM、.NET矿建通信。

python的易用性和强大的内置工具和第三方库使得编程成为一种乐趣而不是琐碎的重复劳动。

猜你喜欢

转载自www.cnblogs.com/songxuexiang/p/10972736.html