操作 MySQL - 2

###获取字典类型

cur = coon.cursor(cursor = pymysql.cursors.DictCursor) #建立游标;指定 cursor 类型为字典类型


###fetchall()、fetchone()、fetchmany()

fetchall() #获取到这个sql 执行的所有结果,它把数据库里面的每一行数据放到一个 list 里面
如:[['1','2','3']] [{},{},{}]

fetchone() #fetchone() #获取到这个sql执行的一条结果,它返回就只是一条数据

  如果sql语句执行的结果是多条数据的时候,那就用fetchall()
  如果你能确定sql执行的结果就只有一条,那么就用fetchone()


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


###cur.description -- 获取数据库字段名

cur.description 获取的是二维元组表的描述,元组里面第一个数即为字段名

例:[filed[0] for filed in cur.description] -- 通过此方法获取字段名


例:(通用导出)

需求:只要你传入一个表名,就能把所有的数据导入出来,字段名是excel的表头
  1、要动态获取到表的字段 cur.description能获取到表的字段
  fileds = [ filed[0] for filed in cur.description ]
  2、获取数据了 select * from "%s" % table_name
  3、循环写入excel

import pymysql,xlwt


def export_excel(table_name):
  host, user, passwd, db = 'xxx.xxx.xxx.xxx', 'xxx', 'xxxxxx', 'xxx'
  coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8')
  cur = coon.cursor() # 建立游标,指定cursor类型返回的是字典
  sql = 'select * from %s ;'%table_name
  cur.execute(sql) # 执行sql
  fileds = [filed[0] for filed in cur.description] #所有的字段
  all_data = cur.fetchall()
  book = xlwt.Workbook()
  sheet = book.add_sheet('sheet1')
  for col,filed in enumerate(fileds): #写表头的;enumerate 可以自动计算下标+取值
    sheet.write(0,col,filed)
  '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  等同:
  col = 0
  for filed in fileds:
    sheet.write(0,col,filed)
    col += 1
  '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  row = 1 #行数
  for data in all_data: #行
    for col, filed in enumerate(data): # 控制列
      sheet.write(row, col, filed)
    row+=1#每次写完一行,行就加1
  book.save('%s.xls'%table_name)


export_excel('app_student')

猜你喜欢

转载自www.cnblogs.com/lynn-chen/p/9001156.html
今日推荐