ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 实例:用户登录 **创建用户表userinfos** * 表结构如下 * id * uname * upwd * isdelete * 注意:需要对密码进行加密 * 如果使用md5加密,则密码包含32个字符 * 如果使用sha1加密,则密码包含40个字符,推荐使用这种方式 ~~~ create table userinfos( id int primary key auto_increment, uname varchar(20), upwd char(40), isdelete bit default 0 ); ~~~ ## 加入测试数据 * 插入如下数据,用户名为123,密码为123,这是sha1加密后的值 ~~~ insert into userinfos values(0,'123','40bd001563085fc35165329ea1ff5c5ecbdbbeef',0); ~~~ ## 接收输入并验证 * 创建testLogin.py文件,引入hashlib模块、MysqlHelper模块 * 接收输入 * 根据用户名查询,如果未查到则提示用户名不存在 * 如果查到则匹配密码是否相等,如果相等则提示登录成功 * 如果不相等则提示密码错误 ~~~ #encoding=utf-8 from MysqlHelper import MysqlHelper from hashlib import sha1 sname=raw_input("请输入用户名:") spwd=raw_input("请输入密码:") s1=sha1() s1.update(spwd) spwdSha1=s1.hexdigest() sql="select upwd from userinfos where uname=%s" params=[sname] sqlhelper=MysqlHelper('localhost',3306,'test1','root','mysql') userinfo=sqlhelper.get_one(sql,params) if userinfo==None: print '用户名错误' elif userinfo[0]==spwdSha1: print '登录成功' else: print '密码错误' ~~~ ## python3代码: ~~~ #!/usr/bin/env python # -*- coding: utf-8 -*- ''' @Time : 5/15/18 1:43 AM @Author : haibo @File : Login.py ''' # 用自己封装的MysqlHelper 模拟用户登录 from MysqlHelper import MysqlHelper import hashlib # 接收用户输入 name = input("请输入用户名:") pwd = input("请输入密码:") params = [name] # 对密码加密 s1 = hashlib.sha1() s1.update(pwd.encode("utf-8")) spwd = s1.hexdigest() # 根据用户名来查询密码 sql = "select upwd from userinfos where uname=%s" test = MysqlHelper("localhost", 3306, "python3", "root", "haibo") result = test.all(sql, params) if len(result) == 0: print("用户名错误!") elif result[0][0] == spwd: print("登录成功!") else: print("密码错误!") ~~~