1.流程图
2.加密
- 注意:需要对密码进行加密
- 如果使用md5加密,则密码包含32个字符
- 如果使用sha1加密,则密码包含40个字符,推荐使用这种方式
3.创建表
mysql> create table users( -> id int auto_increment primary key not null, -> name varchar(20), -> passwd char(40));
加入测试数据
- 插入如下数据,用户名为abc,密码为123,这是sha1加密后的值
mysql> insert into users values(0,'abc','40bd001563085fc35165329ea1ff5c5ecbdbbeef');
4.程序
1)版本1:框架
#-*- coding:utf-8 -*- from MysqlHelper import MysqlHelper #获取用户输入 user_name = raw_input("请输入用户名:") passwd = raw_input("请输入密码:") # 匹配数据库 login = MysqlHelper('localhost',3306,'root','mysql','py31') sql = 'select %s from users where name=%s' result = login.all(sql,[passwd,user_name]) print(result)
#判断正确错误
2)版本2:判断用户名错误
#-*- coding:utf-8 -*- from MysqlHelper import MysqlHelper #获取用户输入 user_name = raw_input("请输入用户名:") passwd = raw_input("请输入密码:") # 匹配数据库 login = MysqlHelper('localhost',3306,'root','mysql','py31') sql = 'select %s from users where name=%s' result = login.all(sql,[passwd,user_name]) print(result) #((u'123',),) #判断正确错误 if len(result) == 0: print("用户名错误")
3)版本3:加密
# hashlib 包源码 >>> import hashlib >>> m = hashlib.md5() >>> m.update("Nobody inspects") >>> m.update(" the spammish repetition") >>> m.digest() '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' More condensed: >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
password = sha1() password.update(passwd) password = password.hexdigest() print(password)
4)版本4:判断
#-*- coding:utf-8 -*- from MysqlHelper import MysqlHelper from hashlib import sha1 #获取用户输入 user_name = raw_input("请输入用户名:") passwd = raw_input("请输入密码:") # >>> import hashlib # >>> m = hashlib.md5() # >>> m.update("Nobody inspects") # >>> m.update(" the spammish repetition") # >>> m.digest() # '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' # # More condensed: # # >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() # 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' #对密码加密 password = sha1() password.update(passwd) password = password.hexdigest() print(password) # 匹配数据库 login = MysqlHelper('localhost',3306,'root','mysql','py31') sql = 'select passwd from users where name=%s' result = login.all(sql,[user_name]) print(result) #((u'123',),) #print(result[0][0]) for test #判断正确错误 if len(result) == 0: print("用户名错误") elif result[0][0] == password: print("登陆成功") else: print("密码错误")
5.老师版本
#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 '密码错误'