Python操作MySQL數據庫實現注冊和登錄


python操作數據庫的基本步驟:

 

首先打開local,,創建qqq數據庫。

新建查詢,輸入sql語句創建sh_users表

1 create table sh_users( 2 id int unsigned primary key auto_increment not null, 3 username varchar(20) not null, 4 password char(40) not null, 5 is_delete bit default 0
6 ) 

刷新表頁面,輸入sql語句嘗試插入

1 insert into sh_users (username, password) values ('r速22t', 'f74e2')

 

接下來就可以寫代碼了!

 1 from hashlib import *
 2 import pymysql  3 
 4 
 5 # 獲取數據庫連接對象
 6 def mysql_conn():  7     conn = pymysql.connect(host='127.0.0.1', user='root', passwd='111111', db='qqq')  8     return conn  9 
10 
11 def register(): 12     try: 13         # 獲取數據庫連接對象
14         conn = mysql_conn() 15         # 獲取數據庫操作cursor(游標)
16         cur = conn.cursor() 17         # 編寫查詢的sql語句
18         select_sql = f'select password from sh_users where username = "{u_name}"'
19         # 執行sql語句
20  cur.execute(select_sql) 21         # 獲取執行結果 fetch_one(),判斷結果
22         res = cur.fetchone() 23         # 如果res返回None 表示沒有找到數據,不存在可注冊,存在注冊失敗
24         if res is not None: 25             print('用戶名已存在,注冊失敗', res) 26         else: 27             print('該用戶名可以使用') 28             # 注冊-> 插入數據,手動commit
29             insert_sql = 'insert into sh_users (username, password) values (%s,%s)'
30             insert_params = [u_name, sha_pwd] 31  cur.execute(insert_sql, insert_params) 32  conn.commit() 33             print('注冊成功', u_name) 34         # 關閉連接
35  cur.close() 36  conn.close() 37     except Exception as e: 38         print(e) 39 
40 
41 def login(): 42     try: 43         conn = mysql_conn() 44         cur = conn.cursor() 45         select_sql = f'select password from sh_users where username = "{u_name}"'
46  cur.execute(select_sql) 47         res = cur.fetchone() 48         if res is None: 49             # 登錄:根據用戶名沒有獲取密碼
50             print('用戶名錯誤,登錄失敗') 51         else: 52             # res有值,用戶名正確,判斷密碼正確與否
53             m_pwd = res[0] 54             print(m_pwd, '===========================') 55             if m_pwd == sha_pwd: 56                 print('登錄成功', u_name) 57             else: 58                 print('密碼錯誤,登錄失敗') 59         # 關閉連接
60  cur.close() 61  conn.close() 62     except Exception as e: 63         print(e) 64 
65 
66 if __name__ == '__main__': 67     u_name = input('請輸入用戶名') 68     u_pwd = input('請輸入密碼') 69 
70     # sha1加密
71     s1 = sha1() 72  s1.update(u_pwd.encode()) 73     sha_pwd = s1.hexdigest() 74     print(sha_pwd) 75 
76     # register()
77     login()

 

這里用了兩種字符串格式化操作,sql語句里“=”號后的引號要注意


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM