1. 程式人生 > >利用Python上下文管理器執行MySQL查詢

利用Python上下文管理器執行MySQL查詢

關於Python中的上下文管理器可以參考:

https://www.cnblogs.com/huchong/p/8268765.html#undefined

https://www.cnblogs.com/DragonFire/p/6764066.html

下面說明如何利用Python中的上下文管理器執行MySQL查詢:

示例1:

# 匯入pymysql包,用於連線資料庫
import pymysql

sqlx = 'select goods_id,goods_name from goods where goods_id<10'

def get_conn(**kwargs):
    return pymysql.connect(host=kwargs.get('host','localhost'), #'host'是鍵,'localhost'是預設值
                          user=kwargs.get('user'),
                          passwd=kwargs.get('passwd'),
                          database=kwargs.get('database'),
                          port=kwargs.get('port',3306),         #'port'是鍵,3306是預設值
                          charset=kwargs.get('charset','utf8'))

# 建立資料庫連線物件
conn = get_conn(user='root',passwd='883721',database='test',charset='utf8')
with conn.cursor() as cur:
    cur.execute(sqlx)
    print(cur.fetchone())

# 上述程式碼的查詢結果為:
(4, 'HTCN85原裝充電器         ')

上述程式碼中with語句裡的遊標cur就是一個上下文管理器物件,with語句結束時,遊標cur會被自動關閉,避免了對資料庫中的表進行查詢操作後要手動關閉遊標的麻煩。但是這種寫法只是在with語句結束時自動關閉了遊標,資料庫連線並沒有同時自動斷開。假如想要實現在with語句結束時,遊標自動關閉,資料庫連線也自動斷開,我們可以通過自定義上下文管理器物件達到這個目的。如下示例所示:

示例2:

import pymysql

class DataBase(object):
    
    def __init__(self,name,password):
        # 建立資料庫連線
        self.conn = pymysql.connect('localhost','root',str(password),str(name),charset='utf8')
        # 建立cursor物件
        self.cursor = self.conn.cursor()
        
    def __enter__(self):
        return self.cursor  # 返回cursor物件,且這個cursor物件會被賦給with語句中as後面的變數
    
    def __exit__(self,exc_type,exc_value,traceback):
        self.cursor.close()    # 關閉遊標物件
        self.conn.close()      # 斷開資料庫連線
        

def main():
    with DataBase('test',883721) as db:
        db.execute('select * from employee')   # 執行sql語句
        content = db.fetchall()                # 獲取資料(db中儲存著查詢結果集)
        
    for info in content:
        print(info)
        
if __name__ == '__main__':
    main()

其他參考:

https://mp.weixin.qq.com/s?__biz=MjM5MTYwMjI3Mw==&mid=2652092269&idx=1&sn=ef2ef4251ed7a34abad87a26c9a217ff&chksm=bd5414638a239d75eaf02f1b41cbd7aa4ebec95a1080e5953a19d20ac8d79b8dfc245ae10b57&scene=21#wechat_redirect

PS:本文為博主原創文章,轉載請註明出處。