python中登录、注册操作数据库

# 1、注册、登录
# 1、注册的时候存账户密码到数据库里面,密码存密文,要加盐
# 2、登录的时候账号、密码从数据里面取,登录失败一次,错误次数 + 1,错误次数大于3不让登录
# 1、建表 id,username,password,error_count
# 2、账号不存在,并且2次输入的密码是一致,就插入到数据库里面
# select * from nhy_user where username='%s' % username


# 1、账号密码
# 2、select password,error_count from nhy_user where username = '%s' % username
# 3、取到error_count,判断是否大于3
# 4、把用户输入的密码MD5一下,和数据库里面存的密码对比

import pymysql, hashlib


def op_mysql(sql: str):
mysql_info = {
'host': '***.24.3.40',
'port': 3306,
'password': '***',
'user': 'jxz',
'db': 'jxz',
'charset': 'utf8',
'autocommit': True
}
result = '执行完成'
conn = pymysql.connect(**mysql_info)
cur = conn.cursor(pymysql.cursors.DictCursor) # 建立游标
cur.execute(sql)
if sql.strip().lower().startswith('select'):
result = cur.fetchone()
# result = cur.fetchall()
cur.close()
conn.close()
return result


def md5(s, salt='$!@#$12232'):
s = (str(s) + salt).encode()
m = hashlib.md5(s) # 加密
return m.hexdigest()


def register():
for i in range(3):
username = input('username:').strip()
passwd = input('password:').strip()
cpasswd = input('cpassword:').strip()
if username and passwd and cpasswd:
if passwd == cpasswd:
sql = "select * from nhy_user where username='%s';" % username
if op_mysql(sql):
print('用户已经存在!')
else:
md5_password = md5(passwd)
sql2 = 'insert into nhy_user (username,password) value ("%s","%s");' % (username, md5_password)
op_mysql(sql2)
print('注册成功!')
else:
print('两次密码输入不一致')
else:
print('账号/密码不能为空')


def login():
username = input('username:').strip()
passwd = input('passwd:').strip()
if username and passwd:
sql = "select password,error_count from nhy_user where username = '%s'" % username
res = op_mysql(sql)
print('res======', res)
if res:
if res.get('error_count') > 2:
print('用户已经被锁定')
else:
new_passwd = md5(passwd)
if res.get('password') == new_passwd:
print('登录成功!')
else:
print('密码输入错误!')
count = res.get('error_count') + 1
sql2 = 'update nhy_user set error_count = %s where username = "%s";' % (
count, username
)
op_mysql(sql2)
else:
print('用户不存在')


def clear_error_count():
username = input('username:').strip()
sql2 = 'update nhy_user set error_count = 0 where username = "%s";' % username
op_mysql(sql2)


login()
# clear_error_count()

猜你喜欢

转载自www.cnblogs.com/skyxiuli/p/10848373.html