網站首頁 編程語言 正文
前言
在上下文管理器協議的過程中,涉及到兩個魔術方法__enter__方法 和 __exit__方法
- 在python中所有實現了上下文管理器協議的對象 都可以用使用with操作
- with啟動了對象的上下文管理器
上下文管理器協議:
- __enter__方法: 進入enter方法返回的結果被as后面的變量接收
- exit: 退出with中所有的語句執行完畢執行 執行 exit
實現一個簡單的文件操作來看下上下文管理器協議:
class MyOpen:
?? ?# 實例化
? ? def __init__(self, filename, mode, encoding):
? ? ? ? self.filename = filename
? ? ? ? self.mode = mode
? ? ? ? self.encoding = encoding
? ? def __enter__(self):
? ? ? ? print("---enter---方法")
? ? ? ? # 執行文件打開操作
? ? ? ? self.f = open(self.filename, self.mode, encoding=self.encoding)
? ? ? ? return self.f
? ? def __exit__(self, exc_type, exc_val, exc_tb):
? ? ? ? """
? ? ? ? :param exc_type: 異常類型
? ? ? ? :param exc_val: 異常信息
? ? ? ? :param exc_tb: 異常溯源對象
? ? ? ? :return:
? ? ? ? """
? ? ? ? print('----enter---')
? ? ? ? self.f.close()
with MyOpen('hr.txt', 'w', encoding='utf-8') as f:
? ? print(f.write('當前打開了文件,寫入了數據:23323232'))
用pymysql實現一個操作數據庫的類,實現上下文管理器協議,實現退出上下文時,自動關閉游標,斷開連接
todo:版本1
# todo:版本1:
class mysql_db(object):
? ? #實例化屬性
? ? def __init__(self):
1.連接數據庫
? ? ? ? self.cou = pymysql.connect(
? ? ? ? ? ? host= "數據庫主機地址", ?
? ? ? ? ? ? port= 端口, ?
? ? ? ? ? ? user="登錄數據庫的賬號", ?
? ? ? ? ? ? password="登錄數據庫的密碼",?
? ? ? ? ? ? database="數據庫名稱", ?
? ? ? ? ? ? charset='utf8', ? ? 編碼格式
? ? ? ? ? ? cursorclass=pymysql.cursors.DictCursor ? ? 將默認的元組格式轉換成字典格式輸出
? ? ? ? )?
2.創建游標
? ? ? ? self.cur = self.cou.cursor()
? ? def __enter__(self):
? ? ? ? return self.cur ? ? ? 返回cur對象
? ? def __exit__(self, exc_type, exc_val, exc_tb):
? ? ? ? """
? ? ? ? :param exc_type: 異常類型
? ? ? ? :param exc_val: 異常信息
? ? ? ? :param exc_tb: 異常溯源對象
? ? ? ? :return:
? ? ? ? """
? ? ? ? #關閉游標
? ? ? ? self.cur.close()
? ? ? ?# 關閉數據庫連接
? ? ? ? self.cou.close()
def Obtain_one_date():
? ? with mysql_db() as db:
? ? ? ? db.execute('select * from t_customer LIMIT 4') ? ? 使用execute方法進行查詢語句
? ? ? ? content = db.fetchone() ?返回一條數據的查詢的結果
? ? ? ? print(content)
# 函數調用
Obtain_one_date()
todo:版本2
sql = 'select * from t_customer LIMIT 4'
def mysql_db1(**kwargs):
? ? return pymysql.connect(host=kwargs.get('host', 'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?user=kwargs.get("user",'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?passwd=kwargs.get("passwd",'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?database=kwargs.get("database",'xxxx'),
? ? ? ? ? ? ? ? ? ? ? ? ? ?port=kwargs.get('port', xxxx),
? ? ? ? ? ? ? ? ? ? ? ? ? ?charset=kwargs.get('charset', 'utf8'))
1.創建數據庫連接對象
cou = mysql_db1()
2.創建游標
with cou.cursor() as cu:
? ? cu.execute(sql) ? ? ?使用execute方法進行查詢語句
? ? commt = cu.fetchone() ? ? 返回一條數據的查詢的結果
? ? print(commt)
# 函數調用
mysql_db1()
原文鏈接:https://blog.csdn.net/qq_40236497/article/details/125415201
相關推薦
- 2022-05-22 xampp安裝后Apache無法啟動解決辦法_Linux
- 2023-07-08 vs編譯運行報錯:未聲明的標識符
- 2022-11-26 Python?Django教程之模板的使用_python
- 2024-07-13 通過maven基于springboot項目構建腳手架archetype
- 2023-01-14 GoLang并發機制探究goroutine原理詳細講解_Golang
- 2023-10-11 hutool工具類 | huTool的基本使用
- 2022-07-11 lambda表達式和Stream
- 2022-11-01 AndroidView與Compose框架交互實現介紹_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支