python——連接Redis數據庫


建立與Redis的連接

import redis

pool = redis.ConnectionPool(host='localhost', port=6379)
# 默認情況下每創建一個Redis實例都會構造出一個ConnectionPool實例,每一次訪問redis都會從這個連接池得到一個連接,操作完成后會把該連接放回連接池(連接並沒有釋放),可以構造一個統一的ConnectionPool,在創建Redis實例時,可以將該ConnectionPool傳入,那么后續的操作會從給定的ConnectionPool獲得連接,不會再重復創建ConnectionPool。
# 默認情況下沒有設置keepalive和timeout,建立的連接是blocking模式的短連接。
# 不考慮底層tcp的情況下,連接池中的連接會在ConnectionPool.disconnect中統一銷毀。

r = redis.Redis(connection_pool=pool)

或

r = redis.StrictRedis(host='localhost', port=6379)

操作

方式一:根據數據類型的不同,調用相應的方法,完成讀寫

r.set('name','hello')

temp = r.get('name')

print(temp)

>> b'hello'  # b代表二進制 .decode() 一下就好了

方式二:pipline

緩沖多條命令,然后一次性執行,減少服務器-客戶端之間TCP數據庫包,從而提高效率

pipe = r.pipeline()

pipe.set('name', 'world')

pipe.get('name')

pipe.execute()      # 一次性執行緩存的命令

示例:用戶登錄

  • 業務過程如下:
  • 輸入用戶名、密碼
  • 密碼加密
  • 判斷redis中是否記錄了用戶名,如果有則成功
  • 如果redis中沒有用戶名,則到mysql中查詢
  • 從mysql中查詢成功后,將用戶名記錄到redis中
import pymysql,redis

username = input("請輸入用戶名:")
password = input("請輸入密碼:")

pool = redis.ConnectionPool(host='localhost', port=6379)
r = redis.Redis(connection_pool=pool)     # 創建redis連接

if r.get(username):
    if password == r.get(username).decode():    # python3獲取的是bytes類型,要decode一下
        print('redis')
        print("登錄成功!")
    else:
        print("密碼輸入錯誤")

else:
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxx', db='xingedb')     # 創建mysql連接
    cursor = conn.cursor()     # 創建游標
    try:
        cursor.execute('select password from cmdb_userinfo where username = %s;',[username,])      # 執行SQL語句,並返回受影響的行數
        pwd = cursor.fetchone()[0]
        if pwd == password:
            print('mysql')
            print('登錄成功!')
            r.set(username, password)
        else:
            print("密碼輸入錯誤")
    except Exception as e:
        print("您輸入的用戶不存在")
    conn.commit()    # 提交,不然無法保存新建或者修改的數據
    cursor.close()     # 關閉游標
    conn.close()    # 關閉連接

  


免責聲明!

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



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