1. 為你的庫准備數據
drop database db1; # 小心
create database db1 charset utf8;
use db1;
create table user(id int primary key auto_increment, username varchar(255) not null unique, password varchar(255), unique key(username)) engine=innodb;
insert into user(username, password) values('yang','123'),('egon', '123');
2. 函數版本
# coding: utf-8
import pymysql
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='1234',
database='db1,
charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
def sql_select(username, password):
sql = 'select * from user where username=%s and password=%s'
rows = cursor.execute(sql, (username, password))
if rows:
return True
def sql_auth(username):
sql = 'select * from user where username=%s'
rows = cursor.execute(sql, (username,))
if rows:
return True
def sql_insert(username, password):
sql = 'insert into user values(%s, %s)'
cursor.execute(sql, (username, password))
conn.commit()
def register():
while True:
username = input("[返回上一層:B/b]請輸入用戶賬號: ").strip()
if username.lower() == 'b':
break
flag = sql_auth(username)
if flag:
print('對不起! 用戶已存在!')
continue
password = input("請輸入用戶密碼: ").strip()
re_password = input("請確認用戶密碼: ").strip()
if not all([username, password]):
print("對不起, 以上內容輸入不能為空!")
continue
if password == re_password:
sql_insert(username, password)
print(f"注冊成功! 用戶:{username}")
else:
print('對不起, 2次密碼輸入不一致!')
def login():
while True:
username = input("[返回上一層:B/b]請輸入用戶賬號: ").strip()
if username.lower() == 'b':
break
password = input("請輸入用戶密碼: ").strip()
if not all([username, password]):
print("對不起, 登錄失敗!")
continue
flag = sql_select(username, password)
if flag:
print(f"登錄成功! 用戶:{username}")
break
else:
print("對不起, 登錄失敗!")
func_dic = {
'1': register,
'2': login,
}
def run():
while True:
print("""
============ 小功能 ============
1. 注冊
2. 登錄
============ end ============
""")
cmd = input('[退出:Q/q]根據編號選擇相應的功能: ').strip()
if cmd.lower() == 'q':
break
if cmd not in func_dic:
print("對不起, 輸入范圍有誤!")
continue
func_dic[cmd]()
if __name__ == '__main__':
run()python
3. 面向對象版本
# coding: utf-8
import pymysql
class MySQLDBHandle:
def __init__(self,
host='127.0.0.1', port=3306,
user='root', password='1234',
database='db1', charset='utf8'):
self.conn = pymysql.connect(
host=host,
port=port,
user=user,
password=password,
database=database,
charset=charset
)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
def insert(self, username, password):
"""插入操作"""
try:
sql = 'insert into user(username, password) values(%s, %s)'
self.cursor.execute(sql, (username, password))
self.conn.commit()
return True
except Exception as e:
self.conn.rollback()
return e
def select(self, username, password=None, function_type=None):
"""查詢操作"""
if function_type == 'auth':
sql = 'select * from user where username=%s'
affected_rows = self.cursor.execute(sql, (username,))
elif function_type == 'login':
sql = 'select * from user where username=%s and password=%s'
affected_rows = self.cursor.execute(sql, (username, password))
else:
return
if affected_rows:
return True
def _close_cursor(self):
"""關閉游標"""
self.cursor.close()
def _close_conn(self):
"""關閉連接"""
self.conn.close()
def __del__(self):
self._close_cursor()
self._close_conn()
class MyFuncation:
def __init__(self, handle=MySQLDBHandle()):
self.handle = handle
self.func_dic = {
'1': self.register,
'2': self.login,
}
self.interactive()
def register(self):
while True:
username = input("[返回上一層:B/b]請輸入用戶賬號: ").strip()
if username.lower() == 'b':
break
flag = self.handle.select(username, function_type='auth')
if flag:
print('對不起! 用戶已存在!')
continue
password = input("請輸入用戶密碼: ").strip()
re_password = input("請確認用戶密碼: ").strip()
if not all([username, password]):
print("對不起, 以上內容輸入不能為空!")
continue
if password == re_password:
flag = self.handle.insert(username, password)
if flag is True:
print(f"注冊成功! 用戶:{username}")
else:
print("對不起!", flag)
else:
print('對不起, 2次密碼輸入不一致!')
def login(self):
while True:
username = input("[返回上一層:B/b]請輸入用戶賬號: ").strip()
if username.lower() == 'b':
break
password = input("請輸入用戶密碼: ").strip()
if not all([username, password]):
print("對不起, 登錄失敗!")
continue
flag = self.handle.select(username, password, function_type='login')
if flag:
print(f"登錄成功! 用戶:{username}")
break
else:
print("對不起, 登錄失敗!")
def interactive(self):
while True:
print("""
============ 小功能 ============
1. 注冊
2. 登錄
============ end ============
""")
cmd = input('[退出:Q/q]根據編號選擇相應的功能: ').strip()
if cmd.lower() == 'q':
break
if cmd not in self.func_dic:
print("對不起, 輸入范圍有誤!")
continue
self.func_dic[cmd]()
if __name__ == '__main__':
MyFuncation()