資源簡介
自己在學(xué)習(xí)pyton時寫的一個小程序,實現(xiàn)從MySQL中抽取數(shù)據(jù),實現(xiàn)注冊和登陸,修改密碼等。
代碼片段和文件信息
#!/usr/bin/python3
import?MySQLdb
import?hashlib
def?Register(username?password):
#?調(diào)用hashlib里的方法,生成哈希值
????md5?=?hashlib.md5()
????#md5.update(password?+?‘wpy‘?+?username)
????md5.update(password.encode(“utf8“))
????md?=?md5.hexdigest()
#?生成哈希值
????realpassword?=?md
#?insert進數(shù)據(jù)庫
????sql?=?“INSERT?INTO?LOGIN(USERNAME?PASSWORD)?VALUES(‘%s‘?‘%s‘)“?%?(username?realpassword)
????try:
????????cursor.execute(sql)
#?必須commit,否則數(shù)據(jù)庫不會更新
????????db.commit()
????except:
????????db.rollback()
def?Login(username?password):
#?與Register()里生成哈希值的方法一樣
????md5?=?hashlib.md5()
????#md5.update(password?+?‘wpy‘?+?username(“utf8“))
????md5.update(password.encode(“utf8“))
????md?=?md5.hexdigest()
????realpassword?=?md
????sql?=?“SELECT?PASSWORD?FROM?LOGIN?WHERE?USERNAME?=?‘%s‘“?%?(username)
????cursor.execute(sql)
#?username是主鍵,至多有一條紀(jì)錄
????pwd?=?cursor.fetchone()[0]
#?返回布爾值
????if?pwd?==?realpassword:
????????return?True
????else:
????????return?False
def?Update(username?password):
????md5?=?hashlib.md5()
????#md5.update(password?+?‘wpy‘?+?username)
????md5.update(password.encode(“utf8“))
????print?(“更新數(shù)據(jù)“)
????md?=?md5.hexdigest()
????realpassword?=?md
????sql?=?“UPDATE?LOGIN?SET?PASSWORD?=?‘%s‘?WHERE?USERNAME?=?‘%s‘“?%(realpassword?username)
????try:
????????cursor.execute(sql)
????????db.commit()
????except:
????????db.rollback()
????????db?=?MySQLdb.connect(“127.0.0.1“?“(root)“?“(123456)“?“text“)
????????cursor?=?db.cursor()
????????cursor.execute(“CREATE?TABLE?LOGIN(USERNAME?VARCHAR(20)?PRIMARY?KEY?PASSWORD?VARCHAR(40))“)
????????
????????
#?最外面的一層循環(huán),控制系統(tǒng)的結(jié)束
while?True:
#?根據(jù)用戶的輸入,決定系統(tǒng)是否終止
????db?=?MySQLdb.connect(“l(fā)ocalhost“?“root“?“123456“?“text“)
????cursor?=?db.cursor()
????start?=?input(“You?want?to?(R)egister?or?(L)ogin?or?(U)pdate?“)
#?判斷
????if?start.lower()?==?‘r‘:
????????while?True:?#用戶可以輸入多次username
????????????username?=?input(“Please?input?your?new?name:“)
????????????sql?=?“SELECT?PASSWORD?FROM?LOGIN?WHERE?USERNAME?=?‘%s‘“?%?username
#?查詢不到結(jié)果返回None
????????????m?=?cursor.execute(sql)
????????????if?m:
????????????????print?(“‘%s‘?has?already?existed.Please?change?your?name.“?%username)
#?輸入錯誤的話重新循環(huán)
????????????????continue
????????????else:
????????????????password?=?input(“Please?input?your?password:“)
????????????????Register(username?password)
????????????????print?(“Register?sucessfully!“)
????????????????break
評論
共有 條評論