Mysql打包及写入数据,读取及保存至xls文档中

打包及写入数据

 import pymysql
 class Con:
     def __init__(self,host,user,password,db,charset):
         self.host=host
         self.user=user
         self.password=password
         self.db=db
         self.charset=charset
     def Connect(self):
         con=pymysql.connect(host=self.host,
                            user=self.user,                            
                            password=self.password,
                            db=self.db,
                            charset=self.charset)
        return con
 con=Con('localhost','root','123123','school','utf8').Connect()
 cur2=con.cursor()
#导入表头
sql="create table if NOT EXISTS ha(姓名 varchar(50) not null," \
      "性别 varchar not null," \
      "语文 int not null," \
      "数学 int not null,"\
      "英语 int not null," \
      "平均分 FLOAT not null," \
      "总分 FLOAT NOT null);"
 cur2.execute(sql)
 con.commit()
 # 导入数据
 cur1=con.cursor()
 def shuju(itit):
     sql2="insert into chengji VALUES ('%s','%s','%d','%d','%d','%d','%d')"
     cur1.execute(sql2%itit)
     con.commit()
 for i in range(len(info)):
     tuple1=tuple(info[i].values())
     print(tuple1)
     shuju(tuple1)

读取及保存至xls文档

import pymysql
import xlwt
con=pymysql.connect(host='localhost',
                    user="root",
                    password="123123",
                    db="movies",
                    charset="utf8")
cur=con.cursor()
sql="select * from movierank"
cur.execute(sql)
# print(all)
list1=[]      #取出表头
k=cur.description
for n in k:
    list1.append(n[0])
print(list1)

all=cur.fetchall()#取其他数据
print(all)
# for i in all:
#     list2.append(i)
# print(list2)
wbk=xlwt.Workbook()     #建表
sheet=wbk.add_sheet('表01')    #新建表单
for i in range(len(list1)):
    sheet.write(0, i, list1[i])  # 写表头
for i in range(1,len(all)+1):
    for j in range(len(list1)):
        sheet.write(i, j, all[i-1][j])
wbk.save('./15.xls')   #保存
print('ok')

你可能感兴趣的:(Mysql打包及写入数据,读取及保存至xls文档中)