python-mysql數據庫登錄與注冊練習


 1 import hashlib,pymysql,datetime
 2 def my_db(sql):
 3     import pymysql
 4     coon = pymysql.connect(
 5         host = '118.24.3.40',user = 'jxz',passwd = '123456',
 6         port = 3306,db = 'jxz',charset = 'utf8'
 7     )
 8     cur = coon.cursor()#建立游標
 9     cur.execute(sql)#執行sql
10     if sql.strip()[:6].upper() == 'SELECT':
11         res = cur.fetchall()
12     else:
13         coon.commit()
14         res = 'ok'
15     cur.close()
16     coon.close()
17     return res
18 
19 def my_md5(str):
20     import hashlib
21     new_str = str.encode()#吧字符串轉成bytes類型
22     m = hashlib.md5()#實例化md5對象
23     m.update(new_str)#加密
24     return m.hexdigest()#獲取返回結果
25 
26 def reg():
27     username = input("username:").strip()
28     pwd = input("pwd:").strip()
29     cpwd = input('cpwd:').strip()
30     if username and pwd and cpwd:
31         sql = 'select * from nhy where name = "%s";'%username
32         res = my_db(sql)
33         if res:
34             print("該用戶已經存在!")
35         else:
36             if pwd == cpwd:
37                 md5_pwd = my_md5(pwd)
38                 insert_sql = 'insert into nhy (name,pwd) values ("%s","%s");'%(username,md5_pwd)
39                 my_db(insert_sql)
40                 print("注冊成功!")
41             else:
42                 print('兩次輸入的密碼不一致!')
43     else:
44         print('必填項不能為空!')
45 
46 def login():
47     username = input('username:').strip()
48     pwd = input('pwd:').strip()
49     if username and pwd:
50         md5_pwd = my_md5(pwd)
51         sql = 'select * from nhy where name = "%s" and pwd = "%s";'%(username,md5_pwd)
52         res = my_db(sql)
53         if res:
54             print("歡迎,登陸成功!今天是%s"%datetime.date.today())
55         else:
56             print('賬號或密碼錯誤')
57     else:
58         print("必填項不能為空!")
59 #login()
60 reg()

 


免責聲明!

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



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