python学习(二十一)加密模块及数据库操作

1、MD5加密

不能直接对字符串加密,要先把字符串转换为bytes类型

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

定义函数,做加密

def my_md5(str):
    new_str=str.encode()#把字符串转换成bytes类型
    #new_str=b'%s'%str #把字符串转换成bytes类型
    m=hashlib.md5()  #实例化MD5对象
    m.update(new_str)  #加密
    return m.hexdigest()  #获取结果返回
print(my_md5('jsjs'))

2、其他加密方式

import hashlib
m=hashlib.sha224()  #各种加密方式,用法一样,只是加密出来的密文不一样
m.update('adasdjks'.encode())
print(m.hexdigest())

3、操作数据库

数据库操作步骤:
1)连接数据库 账号,密码,IP,端口号,数据库

2)建立游标
3)执行sql
4)获取结果
5)关闭游标
6)连接关闭

查询数据库数据:

import pymysql
coon=pymysql.connect(
    host='xxx.xx.x.x',user='jxz',password='123456',
    port=3306,db='jxz',charset='utf8'
#port必须是int类型,charset必须写utf8
)
cur=coon.cursor() #建立游标
cur.execute('select * from stu;')
res=cur.fetchall()#获取所有返回的结果
print(res)
cur.close()  #关闭游标
coon.close() #关闭连接

插入数据:

import pymysql
coon=pymysql.connect(
    host='118.24.3.40',user='jxz',password='123456',
    port=3306,db='jxz',charset='utf8'
#port必须是int类型,charset必须写utf8
)
cur=coon.cursor() #建立游标
cur.execute('insert into stu(id,name,sex) values(12,"liujia","测试")')
coon.commit()
res=cur.fetchall()#获取所有返回的结果
print(res)
cur.close()  #关闭游标
coon.close() #关闭连接

4、函数定义数据库操作

def my_db(host,user,paaaword,db,sql,port3306,charset='utf8'):
    import pymysql
    coon=pymysql.connect(uesr=user,
                         host=host,
                         paaaword=paaaword,
                         db=db,
                         charset=charset,
    )
    cur=coon.cursor()
    cur.execute(sql)
    if sql.strip()[:6].upper()=='SELECT':
        res=cur.fetchall()
    else:
        coon.commit()
        res='ok'
    cur.close()
    coon.close()
    return res
 

猜你喜欢

转载自www.cnblogs.com/emilyliu/p/8983279.html