PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
import pymysql
import xlwt,xlrd
def write_excel(row, data, excel,sheet):##写入excel
f = excel
i = row
status = data
sheet2=sheet
#生成第一行
for j in range(0, len(status)):
sheet2.write(i, j, status[j])
if __name__ == '__main__':
f = xlwt.Workbook() # 创建工作簿
sheet1= f.add_sheet(u'sheet1', cell_overwrite_ok=True) # 创建sheet
data = ['Group', 'sche', 'table', 'column','le','type', 'comment']
write_excel(0, data, f, sheet1)
result=[]
try:
#获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
label =1
conn=pymysql.connect(host='localhost',user='root',passwd='root',db='test',port=3306,charset='utf8')
cur=conn.cursor()#获取一个游标
#cur.execute("select * from `table`;")
sql= "select * from `<table>`;" ##`<table>`是建数据库表是插入语句的格式,表名是<table>,插入语句INSERT INTO `<table>` (`Group`, `sche`, `table`, `column`, `le`, `adv`, `type`, `comment`)
cur.execute(sql)
alldata=cur.fetchall()
for rec in alldata:
#注意int类型需要使用str
##将数据写入excel,对应一行的数据
write_excel(label, [rec[1],rec[2],rec[3],rec[4],rec[5],rec[7],rec[8]], f, sheet1)
label = label+1
#print(rec[1])
cur.close()#关闭游标
conn.close()#释放数据库资源
except Exception as e:
print(e)
f.save('demo.xls') # 保存文件
print("end")
print(label)