python連接MySQL數據庫實現(用戶登錄測試功能)pymysql


pymysql

PyMySQL 是一個純 Python 實現的 MySQL 客戶端操作庫,支持事務、存取過程、批量執行,實現增刪改查等

# 注冊
def register(cursor):
    username = input('請輸入注冊的用戶名').strip()
    password = input('請輸入您的密碼').strip()
    # 驗證用戶名是否已經存在
    sql = 'select * from egg where name=%s'
    # 執行sql語句,篩選在拼接
    cursor.execute(sql, (username,))
    # 獲取所有返回結果
    res = cursor.fetchall()
    # not無數據情況(創建)
    if not res:
        # 插入數據
        sql1 = 'insert into egg(name,password) values(%s,%s)'
        # execute方法篩選再拼接,執行sql語句
        cursor.execute(sql1,(username, password))
        print('用戶:%s注冊成功' % username)
    else:
        print('用戶名已存在')
# 登錄
def login(cursor):
    username = input('請輸入您用戶名').strip()
    password = input('請輸入您的密碼').strip()
    # 先獲取是否存在用戶名數據
    sql = 'select * from userinfo where name=%s'
    # 執行sql語句,篩選在拼接
    cursor.execute(sql,(username,))
    # 獲取所有返回結果
    res = cursor.fetchall()  # 結果是列表套字典
    # 判斷密碼是否存在
    if res:
        # 效驗密碼(索引0 獲取真正的列表里面的字典)
        real_dict = res[0]
        # 校驗密碼
        if password == real_dict.get('password'):
            print('登錄成功')
        else:
            print('密碼錯誤')
    else:
        print('用戶名不存在')


# 連接數據庫
def get_conn():
    # 調任模塊
    import pymysql
    # 創建鏈接(鏈接到數據庫)
    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123',
        database='db_01',
        charset='utf8',
        autocommit=True  # 涉及到增刪改 自動二次確認
    )
    # 生成一個游標對象(操作數據庫)
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 讓數據自動組織成字典
    return cursor


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('暫時沒有當前功能編號')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM