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()

猜你喜欢

转载自www.cnblogs.com/ymany/p/9002875.html