python模块hashlib、xlwt、pymysql

一、xlwt

xlwt是python第三方模块,主要是对excel的写操作。xlwt使用时必须先安装。

1、安装

在操作系统的cmd窗口输入pip install xlwt回车即可在线安装。

安装完成后,在写python使用时,需要引入 import xlwt

2、写excel

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

详细用法可参考https://blog.csdn.net/Tulaimes/article/details/71172778

二、mysql连接

mysql的使用要安装pymysql模块。安装方法同样在cmd窗口输入pip install pymysql.使用的时候要引入import pymysql

mysql连接分几个步骤:

1、连接上数据库

2、创建游标、

3、执行sql

4、获取结果

5、关闭游标

6、关闭连接

示例:select语句

import pymysql
coon = pymysql.connect(
    host='localhost',user='root',passwd='123456',
    port=3306,db='shujuku',charset='utf8'
    #port必须写int类型,
    #charset这里必须写utf8
)
cur = coon.cursor() #建立游标
cur.execute('select * from user;')#执行sql语句
res = cur.fetchall()  #获取所有返回的结果,返回类型是个嵌套元祖
cur.close()#关闭游标
coon.close()#关闭连接

select语句的使用如上。但是update\insert\delete语句操作有些不同,因为他们修改了数据库,所以在操作之后必须commit下

示例:

coon = pymysql.connect(
    host='localhost',user='root',passwd='123456', #host根据要连接数据库的实际ip填写。
    port=3306,db='shujuku',charset='utf8'
    #port必须写int类型,
    #charset这里必须写utf8
)
cur = coon.cursor() #建立游标
cur.execute('insert into user (id,name,passwd) VALUE (1,"aa","123456");')
#如果插入的数据值变量存储的话,可以这么写:cur.execute("insert into user(id,name,passwd' values ('%s','%s','%s');"
%(id,username,passwd))
#其中%(id,username,passwd)必须写在双引号外边。如果写在里边就成了一个字符串了
)
coon.commit()
# delete update insert都必须得coomit cur.close()#关闭游标 coon.close()#关闭连接

mysql用select查出来的表数据,返回的格式是两层元祖。如果想要对数据进行再次操作,就要对这个2层元组操作(('1','小红','123456'),('2','小明','123456'))

示例:将mysql数据库读出来的数据写入excel中

import pymysql,xlwt
def sql_to_excel(res):
    # print(res)
    book=xlwt.Workbook()
    sheet=book.add_sheet('stu')
    sheet.write(0, 0, '编号')  # 行、列、写入的内容
    sheet.write(0, 1, '姓名')
    sheet.write(0, 2, '性别')
    j=1#
    for tuple11 in res:#获取到内层元组
        i = 0  # 列,每次都从第0列开始写
        for t in tuple11:#从内层元组中获取元素,并循环写入每个元素到对应的行,列
            sheet.write(j,i,t)
            i=i+1
        j=j+1
    book.save('user.xls')
conn=pymysql.connect(host='localhost',user='root',passwd='123456',
    port=3306,db='shujuku',charset='utf8')
cur=conn.cursor()
cur.execute('select * from user;')
res=cur.fetchall()
sql_to_excel(res)
cur.close()
conn.close()

三、hashlib

#加密,常见的加密方法md5,生成结果是固定的128 bit字节,通常用一个32位的16进制字符串表示.md5加密是不可解得

hashlib是内置模块,不需要安装,在使用时只需要引入import hashlib

import hashlib
m = hashlib.md5()
passwd = '123456965'
m.update(passwd.encode())   #不能直接对字符串加密,要先把字符串转成bytes类型
print(m.hexdigest())

还有hashlib.sha512,hashlib.sha256等,加密后的字符串更长,更安全,但是相对来说也比较慢

猜你喜欢

转载自www.cnblogs.com/bendouyao/p/8968896.html