流程:
注冊:1.從用戶手里拿到數據 —>2.判斷數據是否符合要求—>3.不符合就要求用戶重新輸入—>4.符合那么就執行數據庫語句(插入數據),插入前需要對數據庫查重—>5.重復返回用戶數據已存在—>6.不重復那么就插入成功並告知用戶注冊成功
登陸:1.從用戶手里拿到數據—>2.判斷數據是否符合要求—>3.不符合就要求用戶重新輸入—>4.符合那么就執行數據庫語句(查詢數據)—>5.有數據判斷密碼是否正確,密碼正確那么就登陸成功—>6.無數據返回用戶不存在
import pymysql import re import hashlib # 建立通道 db = pymysql.connect(host="127.0.0.1", user="root", password="12345678", database="cxtest") # 創建游標 cursor = db.cursor() md5 = hashlib.md5() # 注冊方法 def register(): telephone = input('請輸入手機號:') password = input('請輸入密碼(數字字母下划線6-12位):') # 1.用正則檢驗用戶輸入是否合法 if not (re.match('1[3-8][0-9]{9}$', telephone) and re.match('\w{6,12}$', password)): print('請輸入正確的用戶名或密碼!') return # 2.查詢數據庫中手機號是否已經被注冊 sql = 'select telephone from use_info where telephone = "{}"'.format(telephone) cursor.execute(sql) if cursor.rowcount: print('該手機號已注冊!') return # md5加密 md5.update(password.encode('utf8')) password = md5.hexdigest() try: # print(type(telephone), type(password)) sql = 'insert into use_info values("{}","{}")'.format(telephone, password) cursor.execute(sql) db.commit() print("注冊成功") except: print('注冊失敗!') finally: # 關閉游標 db.close() def login(): # 輸入用戶名和密碼 telephone = input('請輸入手機號:') password = input('請輸入密碼(數字字母下划線6-12位):') if not (re.match('1[3-8][0-9]{9}$', telephone) and re.match('\w{6,12}$', password)): print('請輸入正確的用戶名或密碼!') return sql = 'select telephone,password from use_info where telephone = "{}"'.format(telephone) cursor.execute(sql) if not cursor.rowcount: print("用戶不存在") return md5.update(password.encode("utf-8")) password = md5.hexdigest() if cursor.fetchone()[1] != password: print("請輸入正確的密碼") return print("登陸成功") if __name__ == '__main__': while True: print('請選擇您的操作:') print('1.注冊') print('2.登陸') print('0.退出') choose = input('請輸入您的選擇(1,2,0):') if choose == '1': register() print('注冊成功,即將退出') break elif choose == '2': login() print('登陸成功,即將退出') break elif choose == '0': break
需要注意的情況是: cursor.execute(sql)執行sql語句時,應該是最容易報錯的地方,寫代碼是需要先注意自己數據表的數據類型等。
知識點:正則 md5 pymysql