(十)操作数据库、xlrd、xlwt补充

时间:2020-12-01 15:34:00

一、补充操作数据库:

  1、建立游标时,指定返回的类型是字典 

cur = coon.cursor(cursor=pymysql.cursors.DictCursor) 

  2、cur.fetchall()  #获取到sql执行的全部结果,它把数据库全部数据放到一个list里面

res = cur.fetchall()
#>>>[ [],[],[] ]、[{},{},{}]

  cur.fetchone() #获取到sql执行的一条结果,他返回只有一条数据

res = cur.fetchone()
{'id': 1, 'sex': '女', 'name': 'nny'}

  cur.fetchmany() #能传入一个数,返回多少条数据

res = cur.fetchmany(5) 

  #如果sql语句执行结果是多条的时候,就用fetchall();

  #如果能确定sql执行的结果只取一条数据,就用fetchone()

  【例】:操作数据库函数

#操作数据库函数
def my_db(sql):
import pymysql
host, user, passwd, db = '118.24.3.40','jxz','','jxz'
coon = pymysql.connect(host = host,user = user,port = 3306,
passwd = passwd,db = db,charset ='utf8') #建立连接
#cur = coon.cursor() #建立游标,默认返回的是二维数组
cur = coon.cursor(cursor=pymysql.cursors.DictCursor) #建立游标,指定cursor类型返回的是字典[{'id': 1, 'name': '你好帅', 'sex': '女'}]
cur.execute(sql) #执行sql
if sql.strip()[:6].upper()=='SELECT': #判断sql前几个字母是select,全部转成大写
#res = cur.fetchall() #判断如果是select语句,直接获取sql执行的全部结果[ [],[],[] ]、[{},{},{}]
#res = cur.fetchone() #获取到这个sql执行的一条结果,只返回一条数据{'id': 1, 'sex': '女', 'name': 'nny'}
#res = cur.fetchmany(5) ##能传入一个数,返回多少条数据
#res = cur.description #返回二维数组,取的是表的字段的内容(('id', 3, None, 11, 11, 0, True),('name', 253, None, 20, 20, 0, True))
# fileds = []
# for filed in cur.description: #获取到表字段的内容
# fileds.append(fileds[0]) #循环第一个元素,导入到excel做表头
fileds = [filed[0] for filed in cur.description] #列表生成式的形式,节省代码 >>>['id', 'name', 'sex']
print(fileds)
else:
coon.commit() #判断如果不是select语句,就提交一下
res = 'ok'
cur.close()
coon.close()
return res res = my_db('select * from stu limit 10;')
print(res)

2、enumerate([list1]):自动打印下标和值

fileds = ['id','name','sex','addr']
for index,filed in enumerate(fileds):
print(index,filed)

0 id

1 name

2 sex

3 addr

3、【例】:通用将mysql中的表导出到excel

只要你传入一个表名,就能把所有的数据导出来,字段名是excel的标题

1、动态地获取到表的字段:(表头)

   fileds = [filed[0] for filed in cur.description]

2、获取数据  elect * from "%s"; %table_name

3、循环写入到excel

import xlwt,pymysql
def export_excel(tablename):
host, user, passwd, db = '118.24.3.40', 'jxz', '', 'jxz'
coon = pymysql.connect(host = host,user = user,port = 3306,
passwd = passwd,db = db,charset ='utf8') #建立连接
cur = coon.cursor() #建立游标,返回二维数组
sql = 'select * from %s;' % tablename
cur.execute(sql) #执行sql
fileds = [ i[0] for i in cur.description ] #取到表中的字段(表头)
all_data = cur.fetchall() # 取到表中的所有的数据 book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
# col = 0
# for title in fileds: #将获取的字段,循环写入到excel的表头
# sheet.write(0,col,title) #第0行,列在变
# col += 1
for col,filed in enumerate(fileds): #写表头,enumerate自动循环取下标和列表的值,col=0,1,2...
sheet.write(0,col,filed) #print(all_data) #((1, '小黑马', '男', 28),())
row = 1 #写数据,从第一行开始写数据
for data in all_data: #控制行
for col,filed in enumerate(data): #控制列
sheet.write(row, col, filed) #1,1 1,2 1,3
row += 1 #每次写完一行,行就加1
book.save('%s.xls' % tablename) #将表名作为excel的名字
export_excel('app_student')

4、读excel   ,xlrd

import xlrd
book = xlrd.open_workbook('app_student.xls') #打开一个workbook
sheet = book.sheet_by_index(0) #通过索引定位到sheet页,即sheet1
sheet = book.sheet_by_name('sheet1') #通过sheet页的名字来定位sheet页 print(sheet.cell(0,0).value) #指定sheet页的行和列获取到单元格里面的数据>>>text:'id' #获取一整行/一整列的数据
row_list = sheet.row_values(0) #获取到第0行的内容,即表头>>>['id', 'name', 'sex']
row_list = sheet.row_values(1) #获取到第1行的内容 >>[1.0, '小黑马', '男', 28.0] #获取总共有多少行/列
print(sheet.nrows) #获取到excel表总共有多少行 >>>409(包含一行表头)
for i in range(sheet.nrows): #n行
print(sheet.row_values(i)) #循环获取到每行的数据 print(sheet.ncols) #总共多少列 >>>8
print(sheet.col_values(0)) #获取到第0列的数据 >>>['id', 1.0, 2.0, 3.0]

5、写excel,xlwt

import xlwt
book = xlwt.Workbook()  #新建一个excel
sheet = book.add_sheet('sheet1')   #加一个sheet页
sheet.write(0,0,'姓名')  #第1行、第1列,写入的内容
sheet.write(0,1,'年龄')  #第1行,第2列
sheet.write(0,2,'性别')  #第1行,第3列
book.save('stu.xls')  #保存excel,结尾一定要用xls

6、【例】:循环写到excel

import xlwt
book = xlwt.Workbook()  #新建一个excel
sheet = book.add_sheet('sheet1')   #加一个sheet页
title = ['bugID','name','优先级','描述']
for col,filed in
enumerate(title): #写表头的
   sheet.write(0,col,filed) 
#第0行,下标即每列,值

row = 1 #行数,除去表头
for i in range(1,sheet.nrows):#从除标题外,第2行开始,取每一行的数据
   line = sheet.row_values(i)  #循环取到每一行['001','x','xx','xxx']
   for col,filed
in enumerate(line):  #
写每列数据
      sheet.write(row, col, filed) #(1,0,'001'),(1,1,'x'),(1,2,'xx')
   row += 1
book.save('app_student1.xls')

7、修改excel (需要安装模块xlutils)

  1.先用xlrd模块,打开excel

  2.再用xlutils模块的copy方法,复制一份excel

  3.再修改复制的excel

import xlutils,xlwt,xlrd
from xlutils import copy #这个模块用这种方式导入copy方法
book = xlrd.open_workbook('app_student.xls') #1.先用xlrd模块,打开excel
new_book = copy.copy(book) #2.再用xlutils模块的copy方法,复制一份excel
sheet = new_book.get_sheet(0) #xlutils的方法定位获取到copy的excel的sheet页 sheet.write(0,0,'编号') #对第几行、第几列进行修改
sheet.write(0,1,'名字') lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
for col,filed in enumerate(lis): #循环修改某一行
sheet.write(0,col,filed) new_book.save('app_student.xls')