使用python連接數據庫,實現賬號登錄與注冊功能
import pymysql
# MySQL語句 插入數據行,即注冊行為
register_sql = 'insert into user(name,password) values(%s,%s)'
# MySQL語句 查看name=username的數據行 判斷是否已存在該用戶
check_sql = 'select name from user where BINARY name =%s ' # 加入BINARY關鍵字,可使查詢結果區分大小寫
# check_sql = 'select name from user where name =%s ' # 這種查詢無法區分大小寫
# MySQL語句 查看所有符合該賬號與密碼的用戶 若無則有誤,若有則輸出登錄成功
login_sql = 'select * from user where name=%s and password=%s'
# 連接數據庫函數
def MySQL_conn():
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "root",
password = "123",
database = "day48",
charset = "utf8",
autocommit = True
) # 連接數據庫
# 以字典形式輸出數據 不設置則默認為元組類型輸出
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
return cursor
# 登錄函數
def login(cursor):
while True:
username = input("請輸入用戶名:").strip()
if username.lower == "q":
return
password = input("請輸入密碼:").strip()
res = cursor.execute(login_sql,(username,password)) # 返回值為數據行數,或字典鍵值對個數
if res:
print("登陸成功!")
print('數據行數:',res) # 2
print(cursor.fetchall()) # [{'id': 1, 'name': 'Jil', 'password': '1118'}, {'id': 3, 'name': 'Jil', 'password': '1118'}]
cursor.scroll(-1,"relative") # 相對於光標所在的位置繼續往前移動1位
print(cursor.fetchall()) # 光標位置取到取到最后 [{'id': 3, 'name': 'Jil', 'password': '1118'}]
return
else:
print("用戶名或密碼錯誤!")
# 注冊函數
def register(cursor):
while True:
username = input("注冊用戶名:").strip()
if username.lower == "q":
return
password = input("設定密碼:").strip()
re_password = input("確認密碼:").strip()
if password != re_password:
print("兩次密碼輸入不一致,請重新輸入!")
continue
res = cursor.execute(check_sql,(username))
# print(res)
# print(cursor.fetchall())
if res:
print("用戶名【%s】已存在,請重新輸入!"%username)
continue
else:
cursor.execute(register_sql,(username,password))
print("注冊成功!")
return
if __name__ == '__main__':
cursor = MySQL_conn()
while True:
print("登錄或注冊".center(50,"="))
print('''1、登錄
2、注冊''')
cmd = input("請輸入您需要的操作數:").strip()
if cmd not in ["1","2",'q']:
print("請輸入正確指令!")
if cmd == '1':
login(cursor)
elif cmd == '2':
register(cursor)
else:
break