栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用python对数据库进行分段游标查询,结果生成表格

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用python对数据库进行分段游标查询,结果生成表格

小白学python,记录进程。

# -*- coding:utf-8 -*-
"""
Python 3.7
作者:孙敏
日期:2022年02月17日
"""
import pymysql
from tqdm import tqdm
import re

#填写对应的mysql连接信息
host = 'localhost'
port = 3306
user = 'sunmin'
password = 'sunmin'
database = 'sunmin'
#连接mysql数据库
db =pymysql.connect(host=host,port=port,user=user,password=password,
                         database=database,charset='utf8')
#使用游标
cursor = db.cursor()

#使用sql语句对id进行分段查询database对应数据库中的表,将查询结果生成表格
def output_as_a_excel_table(path,startid,endid,step):
    for i in tqdm(range(startid,endid,step),'进度'):#定义函数
        section = list((i,i+step-1))
        cursor.execute(sql,section)#执行单个sql语句
        record = list(cursor.fetchall())#取出查询语句的第一个元素
        # print(record)
        # 创建一个excel
        result = open(path, 'a+', encoding='gbk')
        # 参数'w'代表往指定表格写入数据,会先将表格中原本的内容清空
        # 参数'a+'代表以读写模式打开文件;如果文件存在,文件指针放在文件的末尾(新写入文件会位于已有内容之后);反之,则创建新文件。
        r=0
        for m in range(len(record)):
            for n in range(len(record[m])):
                result.write(str(record[m][n]))
                result.write('t')  # 't'表示每写入一个元素后,会移动到同行的下一个单元格
            result.write('n')# 换行操作
            r=r+1
        result.close()
        #print(r)#打印行数
if __name__ == '__main__':
    # 设置多个sql语句
    sqllist = ["SELECt name,count(id) FROM `t` where (id between %s and %s) group by name order by count(id) desc"]
    for sql in sqllist:
        startid = 1#设置起始id
        step = 100000#设置步长
        #查找对应表的最大id
        tablename = re.findall("FROM(.*?)where", sql)[0]
        idsql = 'select id from' + tablename + 'order by id desc limit 1'
        cursor.execute(idsql)  # 执行单个sql语句
        endidtuple = cursor.fetchone()  # 取出查询语句的第一个元素
        endid = endidtuple[0]
        print(sql)
        print(endid)
    # 设置存储路径
    path = 'D:探查.xls'
    # 调用函数
    output_as_a_excel_table(path,startid,endid,step)
cursor.close()#关闭游标
db.close()#关闭数据库连接

以上代码可生成不同id段的分组情况,若想得到完整的分组情况,还需要对表格内的数据进行分类汇总,或者另存为xlsx.工作簿后,加上列名,可使用下列代码对特定列名进行分组并求和

import pandas as pd
frame = pd.read_excel("D:探查.xlsx")
# print(frame)
df =  frame.groupby(['某个列名']).sum()#一定要注意中括号内填上对应的列名哦
df.to_excel("D:对应列名分组及数量分布.xls")

完结。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/741007.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号