import pymysql #连接数据库 def get_conn(): con = pymysql.connect( host = '127.0.0.1', port = 3306, user = 'root', password = 'root', database='runoob', charset='utf8', autocommit=True#自动提交 ) cursor = con.cursor(cursor=pymysql.cursors.DictCursor) # 让数据自动组织成字典形式 return cursor #注册 def register(cursor): username = input('请输入用户名:').strip() password = input('请输入密码:').strip() #验证用户名是否存在 sql = "select * from userinfo where name=%s" cursor.execute(sql,(username,)) ret = cursor.fetchall()#这里获取的是上次执行sql的结果 if not ret: # 插入数据 sql = 'insert into userinfo(name,password) values(%s,%s)' # execute方法筛选再拼接,执行sql语句 cursor.execute(sql, (username, password)) print('用户:%s注册成功' % username) else: print('用户名已存在') # 登录 def login(cursor): username = input('请输入您用户名').strip() password = input('请输入您的密码').strip() # 先获取是否存在用户名数据 sql = 'select * from userinfo where name=%s' # sql = "select * from userinfo where name='%s';"% username#容易出现sql注入 # 解决SQL注入的问题只需过滤掉特殊符号 execute方法自带校验SQL注入问题,自动处理特殊符号 # 执行sql语句,筛选在拼接 cursor.execute(sql,(username,)) # cursor.execute(sql) # 获取所有返回结果 res = cursor.fetchall() # 结果是列表套字典 # 判断密码是否存在 if res: # 效验密码(索引0 获取真正的列表里面的字典) real_dict = res[0] # 校验密码 if password == real_dict.get('password'): print('登录成功') else: print('密码错误') else: print('用户名不存在') func_dic = {'1': register, '2': login} # 执行 while True: print(""" 1.注册功能 2.登录功能 """) # 每一次循环都能获取对象(游标) cursor = get_conn() choice = input('请输入功能编号>>>:').strip() if choice in func_dic: # 获取用户输入选择的功能编号 func_name = func_dic.get(choice) # 调用函数 func_name(cursor) else: print('暂时没有当前功能编号')