通过python 连接数据库查询数据,生成表格

该Python脚本主要用于从PostgreSQL数据库中获取数据,使用psycopg2模块连接数据库,然后将查询结果写入Excel文件。它执行一个复杂的SQL查询,计算流入和流出的差值,并将结果按日期排序。最后,数据被保存到名为shuju12.xls的Excel文件中。
摘要由CSDN通过智能技术生成
import psycopg2
import xlwt
import datetime
#
'''
思路:
    1.获取数据库连接
    2.创建excel并初始化
    3.写入excel
    4.保存到本地
'''
#一、获取数据库连接
conn = psycopg2.connect(host="10.107.22.6", port=5432,
                        user="****", password="***",
                        database= '****'#
                        )
# print("数据库连接成功")
#获取游标
curs=conn.cursor()
#SQL语句
#sql = """ select hour,countdate,counttime from  d_mall_hour_count_data where countdate >= date '2023-01-01' and   countdate < date '2023-02-01' """
sql= """ select hour,countdate,counttime,(select sum(innum)-sum(outnum) from d_mall_hour_count_data t2 where t2.countdate=t1.countdate and t2.hour <=t1.hour) as zhiliu from d_mall_hour_count_data t1 where countdate >=date '2022-07-01' and countdate< date '2022-08-01' group by counttime,countdate,hour order by countdate """
#sql = """select "hour",countdate,counttime,(select sum(innum)-sum(outnum) from d_mall_hour_count_data t2 where t2.countdate=t1.countdate and t2."hour"<=t1."hour") as zhiliu from d_mall_hour_count_data t1 where counttime>=date '2022-07-01' and counttime < date '2022-08-01' group by counttime,countdate,"hour" order by counttime """
#curs.mogrify(sql) 
curs.execute(sql)
rows=curs.fetchall()#获取所有数据
print(rows)
#二、初始化excel文件
w=xlwt.Workbook(encoding='utf-8')
style=xlwt.XFStyle()#初始化样式
font=xlwt.Font()#创建字体样式
font.name="微软雅黑"
style.font=font#把字体添加到样式中
ws=w.add_sheet("用户信息",cell_overwrite_ok=True)
#三、把数据写入excel
'''创建excel的列名'''
title="hour,date,datetime,zhiliu"
title=title.split(",")
'''#使用循环写入数据'''
for i in range(len(title)):
    ws.write(0,i,title[i],style)
#开始写入数据
for i in range(len(rows)):
    row=rows[i]
    for j in range(len(row)):
        if row[j]:
            item=row[j]
            ws.write(i+1,j,item,style)

#四、数据保存到本地
path='shuju12.xls'
w.save(path)
conn.close()

print("保存成功!")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值