import pymysql conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123456', database='day48', charset='utf8' ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) while True: msg = ''' ======= 欢迎来到注册登录界面 ======= | 1.注册 | | 2.登录 | | 3.退出 | ============== END ============== ''' print(msg) func_num = input("请输入功能编号:").strip() if func_num == '1': while True: reg_usr = input('请输入用户名:').strip() reg_pwd1 = input("请输入密码:").strip() reg_pwd2 = input("请确认密码:").strip() if not (reg_usr and reg_pwd1 and reg_pwd2): print('输入不能为空') continue if not reg_pwd1 == reg_pwd2: print('两次密码不一致') continue sql = "select * from user where usr=%s;" if cursor.execute(sql, (reg_usr,)): print('用户名已存在') continue sql = 'insert into user(usr,pwd) values(%s, %s)' cursor.execute(sql, (reg_usr, reg_pwd1)) conn.commit() # 提交数据到数据库并保存 print('注册成功') break elif func_num == '2': while True: log_usr = input('请输入账号:').strip() log_pwd = input("请输入密码:").strip() if not (log_usr and log_pwd): print('账号密码不能为空') continue sql = "select * from user where usr=%s and pwd=%s;" if cursor.execute(sql, (log_usr, log_pwd)): print('登录成功!') break print('账号或密码错误!') elif func_num == '3': exit() else: print('输入错误,该命令不存在!')
备注:
如果遇到pymsql连接报错(内容如下):
pymysql.err.OperationalError: (1045, “Access denied for user ‘root’@‘xxx.xxx.xxx.xxx’ (using password: YES)”)
处理步骤:
1、先本地测试数据库账户和密码是否正常登陆,排除密码错误;
2、虽然输入正确的用户名和密码,但是却没有在其他ip地址上访问的权限。需要用root账号登录mysql然后修改权限
# 登陆数据库 mysql -u root -p 登陆密码 # 修改访问权限 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '数据库密码' WITH GRANT OPTION; # 刷新 FLUSH PRIVILEGES;