链接mysql_使用python链接mysql及redis(缓存型数据库)
生活随笔
收集整理的這篇文章主要介紹了
链接mysql_使用python链接mysql及redis(缓存型数据库)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
python鏈接數(shù)據(jù)庫mysql操作,首先我們需要借助第三方庫pymysql。
cmd終端下載:pip install?pymysql
import?pymysql#鏈接數(shù)據(jù)庫db?=?pymysql.connect(host='127.0.0.1',user='root',passwd='123456',db='ergou')cursor = db.cursor() #創(chuàng)建游標cursor.execute("select version()") #查詢數(shù)據(jù)庫版本version?=?cursor.fetchone()????#?把游標攜帶信息賦值給version?print(version) # 查看版本信息cursor.execute('select * from config_total;') #查詢語句data = cursor.fetchone() # 把游標攜帶查詢信息復制給datacursor.execute("update config_total set id = 2 where id = 3;") # 修改數(shù)據(jù)庫db.commit() #數(shù)據(jù)庫提交 data1 = cursor.fetchone() # 游標攜帶信息復制給data1db.rollback()???#回滾?????db.close() #斷開鏈接Redis(緩存型數(shù)據(jù)庫)
redis緩存型數(shù)據(jù)庫,分為兩種模式,哨兵模式,集群模式,且redis一般存在16個實例庫,默認實例庫為0開始,里面數(shù)據(jù)以key+value形式存在。
哨兵模式鏈接
import?redisredis1?=?redis.Redis(host='127.0.0.1',port='8080',db=1)?#?db=1,是指實例庫為1key_name='key_name'????#?key_namekey_value='key_value' # key_valueif?redis1.exists(key_name+?key_value):?????#?先判斷是否存在這個鍵????print(redis1.get(key_name+?key_value))????#?存在就打印value的值????#?redis1.del(key_name+?key_value)???#刪除里面的數(shù)據(jù)else: print('沒有緩存值!')集群模式鏈接
from rediscluster import StrictRedisClusterstartup=[{"host":"173.17.36.11","port":"8080"},?????????{"host":"173.17.36.11","port":"8081"},?????????{"host":"173.17.36.12","port":"8082"},?????????{"host":"173.17.36.12","port":"8083"},?????????{"host":"173.17.36.13","port":"8084"},?????????{"host":"173.17.36.13","port":"8085"}]myredis = StrictRedisCluster(startup_nodes=startup,decode_responses=True)key_name='key_name' # key_namekey_value='key_value' # key_valueif myredis.exists(key+phone): print(myredis.get(key+phone))else:????print('不存在')? ? ? ? ? ? ?我不會告訴你下面就是二狗的微信!
總結
以上是生活随笔為你收集整理的链接mysql_使用python链接mysql及redis(缓存型数据库)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “幽怀竟谁知”上一句是什么
- 下一篇: 下怎么运行sh脚本_基于CentOS7系