Python操作数据库及excel练习二_注册和登录

需求:

1、注册:

数据都存在数据库里面(读取数据库)
注册的时候,密码存的是加密之后的密码(md5加密)
username,pwd,cpwd必填
用户不能重复

2、登录
账号密码登录
输入是明文,数据库是密文
登录成功之后打印当前的日期

实现:

import pymysql,hashlib,datetime

def excute_sql(sql):#连接数据库
    conn = pymysql.connect(host='xxx.xx.x.xx',user='xxx',passwd='123456',db='xx',port=3306,charset = 'utf8')
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()
    res = cur.fetchall()
    cur.close()
    conn.close()
    return res

def MD5(passwd):#MD5加密
    m = hashlib.md5()
    m.update(passwd.encode())
    return m.hexdigest()

def user_exist(username): #判断用户是否存在
    info = excute_sql('select * from dongrui where username = "%s"' % username)
    return info

def register():#注册
    username = input('输入用户名').strip()
    passwd = input('输入密码').strip()
    cpasswd = input('确认密码').strip()
    if username == '' or passwd == '' or cpasswd == '':
        print('用户名密码不能为空')
    elif passwd != cpasswd:
        print('两次输入密码不一致')
    elif user_exist(username):
        print('用户名已存在')
    else:
        passwd_m = MD5(passwd)
        ID = excute_sql('select count(*) from dongrui')[0][0] + 1
        excute_sql('insert into dongrui VALUES("%s","%s","%s")' % (ID, username, passwd_m))
        print('注册成功')

def login():#登录
    username = input('输入用户名').strip()
    passwd = input('输入密码').strip()
    if username == '' or passwd == '':
        print('用户名密码不能为空')
    elif user_exist(username) and user_exist(username)[0][2] == MD5(passwd):
        print('登录成功,欢迎%s,今天是%s' % (username, datetime.date.today()))
    else:
        print('用户名或密码错误')

choice = input('输入你的选择:1、注册,2、登录')
if choice == '1':
    register()
elif choice == '2':
    login()
else:
    print('输入有误')

猜你喜欢

转载自www.cnblogs.com/dongrui624/p/9002394.html