通过配置文件连接数据库查询并写入Excel

本文介绍了一种使用Python从配置文件中读取数据库连接信息,并通过MySQL查询数据,最后将查询结果导出到Excel的方法。文中详细展示了如何利用ConfigParser读取配置文件、MySQLdb进行数据库操作及xlwt库实现Excel文件的创建和数据填充。

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

#encoding:utf-8
'''
Created on 2017年4月12日

@author: ***
'''
import ConfigParser  #读入配置文件
import MySQLdb #链接mysql
import xlwt #Excel

conf_path='F:\\PROJECT\\python\\code\\Study_1\\src\\20170412\\conf.ini'
config = ConfigParser.ConfigParser() ##读配置文件
config.read(conf_path)  #读配置文件
mysql_host = config.get("data","host")  
mysql_port = int(config.get("data","port"))
mysql_user = config.get("data","user");
mysql_passwd = config.get("data","passwd")
mysql_db = config.get("data","db")


#conf.init  数据库链接配置文件示例
'''
[data]
host=***
port=***
...
'''
db = MySQLdb.connect(host = mysql_host, port =mysql_port, user = mysql_user, passwd = mysql_passwd, db = mysql_db, charset='utf8')  #链接数据库

sql='SELECT * FROM `t_bi_brand_ad_activity_mapping'
cursor = db.cursor()
cursor.execute(sql)
result = cursor.fetchall()
excel= xlwt.Workbook()  #创建一EXCLE
sheet=excel.add_sheet('test')  #添加一sheet页名,命名为test
title = cursor.description  #获取列名
#列名写入Excel
for i in range(0,len(title)):
    sheet.write(0,i,title[i][0])
    
#获取数据    
for i in range(1,len(result)+1):
    for j in range(0,len(title)):
        sheet.write(i,j,result[i-1][j]) #result[i-1]获取数据需要从0开始获取,但是写入数据是总行1开始写

excel.save('a4.xls')  

db.close()    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值