Python学习笔记十三_操作数据库、excel

一、操作数据库

1、安装pymysql第三方模块

2、操作数据库

import pymysql
conn = pymysql.connect(
    host='xxx.xx.xx.xx', user='Amy', passwd='123456',
    port=3306, db='jxz', charset='utf8'
)
# 1、连上数据库  账号、密码 ip 端口号 数据库
# port必须写int类型
# charset必须写utf8,不能是utf-8
cur = conn.cursor()#2、建立游标
cur.execute('select * from stu;')#3、执行sql
conn.commit()#除了select,其他sql都需要commit
res =cur.fetchall()#4 、获取结果
print(res)
cur.close()# 5、关闭游标
conn.close()#6、连接关闭

二、操作Excel

1、安装xlrd、xlwt第三方模块

2、写Excel

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

3、读Excel

猜你喜欢

转载自www.cnblogs.com/dongrui624/p/8950540.html
今日推荐