1. 程式人生 > >MySql資料庫與python互動使用者登入(十三)

MySql資料庫與python互動使用者登入(十三)

例項:使用者登入

建立使用者表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 '密碼錯誤'