1. 程式人生 > >pymysql使用者登入(密碼加密)和封裝經典例項

pymysql使用者登入(密碼加密)和封裝經典例項

(1)packaging.py 裡面封裝好方法

import pymysql
import hashlib

class MysqlHelper():
    def __init__(self, host, database, user, password, port=3306,charset='utf8'):
        self.host = host
        self.port = port
        self.database = database
        self.user = user
        self.password = password
        self.charset = charset

    def
connect(self):
self.conn = pymysql.connect(host=self.host, port=self.port, database=self.database, user=self.user, password=self.password, charset=self.charset) self.cursor = self.conn.cursor() def close(self): self.cursor.close() self.conn.close() def
select_one(self, sql, params=[]):
result = None try: self.connect() self.cursor.execute(sql, params) result = self.cursor.fetchone() self.close() except Exception as e: print(e) return result def select_all
(self, sql, params=[]):
result = () try: self.connect() self.cursor.execute(sql, params) result = self.cursor.fetchall() self.close() except Exception as e: print(e) return result def __edit(self, sql, params): count = 0 try: self.connect() count = self.cursor.execute(sql, params) self.conn.commit() self.close() except Exception as e: print(e) return count def insert(self, sql, params=[]): return self.__edit(sql, params) def update(self, sql, params=[]): return self.__edit(sql, params) def delete(self, sql, params=[]): return self.__edit(sql, params) def my_md5(self,pwd): my_md5=hashlib.md5() my_md5.update(pwd.encode('utf-8')) return my_md5.hexdigest()

(2)demo04_使用者登入案例.py 進行呼叫

from packaging import MysqlHelper
import  hashlib

def register():
    name=input('使用者名稱:')
    pwd=input('密碼:')

    helper=MysqlHelper(host='localhost',database='laowang',user='root',password='root')
    ret=helper.insert('insert into t_user(name,pwd) VALUES (%s,%s)',[name,helper.my_md5(pwd)])
    if ret>0:
        print('成功')
    else:
        print('失敗')
def login():
    name = input('使用者名稱:')
    pwd = input('密碼:')

    helper = MysqlHelper(host='localhost', database='laowang', user='root', password='root')
    ret=helper.select_one('select count(*) from t_user where name=%s and ped=%s',[name,helper.my_md5(pwd)])
    if ret[0]>0:
        print('成功')
    else:
        print('失敗')

def main():
    while True:
        choice=input('1、註冊1   2、登入')
        if choice=='1':
            register()
        elif choice=='2':
            login()
if __name__=='__main__':
    main()

附錄-資料庫 t_user
圖1