python MySQL 写入excel

本文介绍了一个Python脚本用于从MySQL数据库提取用户ID、购买金额等数据,并将其写入Excel文件的过程。该脚本在处理大量数据时运行缓慢,通过分析发现原因是未对MySQL表创建索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
#coding=utf-8
import xlwt
import xlrd
import MySQLdb
import os
os.chdir("E:\work")

def lancome15_write_rows():
    #将字段写入到EXCEL新表的第一行
    L = ['Id', 'Amount of money', 'Purchase times']
    for ifs in range(len(L)):
         sheet.write(0,ifs,L[ifs])
    wbk.save('lancome15_result_8.9.csv')
    sql = "SELECT DISTINCT category FROM lancome15_order_online" 
    cursor.execute(sql)
    numrows = int(cursor.rowcount)
    L = []
    for i in range(numrows):
        g = cursor.fetchone()
        sheet.write(0,i+3,g[0])
        L.append(g[0])
    wbk.save('lancome15_result_8.9.csv')
    print L

def lancome15_write_cols():
    sql = "SELECT DISTINCT uid FROM lancome15_order_online" 
    cursor.execute(sql)
    numrows = int(cursor.rowcount)
    sum = 0
    for i in range(numrows):
        g = cursor.fetchone()
        sum += 1
        sheet.write(i+1,0,g[0])
    wbk.save('lancome15_result_8.9.csv')
    print sum

def lancome15_read_excel():
    workbook = xlrd.open_workbook(r'E:\work\lancome15_result_8.9.csv')
    sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始
    rows = sheet1.row_values(0) 
    cols = sheet1.col_values(0) 
    return rows[3::],cols[1::]

def lancome15_result_func():
    result = lancome15_read_excel()
    row_name = result[0] 
    col_name = result[1] 
    for i in range(len(col_name)):
        sql1 = "SELECT SUM(ogn*price), COUNT(oid) FROM lancome15_order_online where uid = '%s'" % (col_name[i])
        cursor.execute(sql1)
        g = cursor.fetchone()           
        sheet.write(i+1,1,g[0])
        sheet.write(i+1,2,g[1])
        for j in range(len(row_name)): 
            sql2 = 'SELECT COUNT("%s") FROM lancome15_order_online where uid = "%s" AND category = "%s"' \
              % (row_name[j], col_name[i], row_name[j]) 
            cursor.execute(sql2)
            f = cursor.fetchone() 
            sheet.write(i+1,j+3,f[0])
    wbk.save('lancome15_result_8.9.csv')

if __name__ == "__main__":
    conn=MySQLdb.connect("localhost","root","111111","work")
    cursor=conn.cursor()
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet('test1',cell_overwrite_ok=True)
    print "Begin"
    lancome15_write_rows()
    lancome15_write_cols()
    lancome15_read_excel()
    lancome15_result_func()
    print "Over"

今天的工作需要从MySQL表提取出以下内容:用户ID、购买金额、购买次数和各个类别的购买次数,将最终结果写入excel表。程序中的lancome15_result_func函数运行极其缓慢,后经请教他人得知MySQL未创建索引的缘故。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值