網站首頁 編程語言 正文
前言
在上下文管理器協(xié)議的過程中,涉及到兩個魔術方法__enter__方法 和 __exit__方法
- 在python中所有實現(xiàn)了上下文管理器協(xié)議的對象 都可以用使用with操作
- with啟動了對象的上下文管理器
上下文管理器協(xié)議:
- __enter__方法: 進入enter方法返回的結果被as后面的變量接收
- exit: 退出with中所有的語句執(zhí)行完畢執(zhí)行 執(zhí)行 exit
實現(xiàn)一個簡單的文件操作來看下上下文管理器協(xié)議:
class MyOpen:
?? ?# 實例化
? ? def __init__(self, filename, mode, encoding):
? ? ? ? self.filename = filename
? ? ? ? self.mode = mode
? ? ? ? self.encoding = encoding
? ? def __enter__(self):
? ? ? ? print("---enter---方法")
? ? ? ? # 執(zhí)行文件打開操作
? ? ? ? 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('當前打開了文件,寫入了數(shù)據(jù):23323232'))
用pymysql實現(xiàn)一個操作數(shù)據(jù)庫的類,實現(xiàn)上下文管理器協(xié)議,實現(xiàn)退出上下文時,自動關閉游標,斷開連接
todo:版本1
# todo:版本1:
class mysql_db(object):
? ? #實例化屬性
? ? def __init__(self):
1.連接數(shù)據(jù)庫
? ? ? ? self.cou = pymysql.connect(
? ? ? ? ? ? host= "數(shù)據(jù)庫主機地址", ?
? ? ? ? ? ? port= 端口, ?
? ? ? ? ? ? user="登錄數(shù)據(jù)庫的賬號", ?
? ? ? ? ? ? password="登錄數(shù)據(jù)庫的密碼",?
? ? ? ? ? ? database="數(shù)據(jù)庫名稱", ?
? ? ? ? ? ? charset='utf8', ? ? 編碼格式
? ? ? ? ? ? cursorclass=pymysql.cursors.DictCursor ? ? 將默認的元組格式轉換成字典格式輸出
? ? ? ? )?
2.創(chuàng)建游標
? ? ? ? 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()
? ? ? ?# 關閉數(shù)據(jù)庫連接
? ? ? ? self.cou.close()
def Obtain_one_date():
? ? with mysql_db() as db:
? ? ? ? db.execute('select * from t_customer LIMIT 4') ? ? 使用execute方法進行查詢語句
? ? ? ? content = db.fetchone() ?返回一條數(shù)據(jù)的查詢的結果
? ? ? ? print(content)
# 函數(shù)調用
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.創(chuàng)建數(shù)據(jù)庫連接對象
cou = mysql_db1()
2.創(chuàng)建游標
with cou.cursor() as cu:
? ? cu.execute(sql) ? ? ?使用execute方法進行查詢語句
? ? commt = cu.fetchone() ? ? 返回一條數(shù)據(jù)的查詢的結果
? ? print(commt)
# 函數(shù)調用
mysql_db1()
原文鏈接:https://blog.csdn.net/qq_40236497/article/details/125415201
相關推薦
- 2022-12-08 C++?float轉std::string?小數(shù)位數(shù)控制問題_C 語言
- 2022-09-25 Linux基礎組件之基于循環(huán)數(shù)組的無鎖隊列
- 2023-08-01 v-model 和 .sync 深度解讀
- 2023-04-12 如何徹底解決python?NameError:name?'__file__'?is?not?defi
- 2022-05-01 教你利用python如何讀取txt中的數(shù)據(jù)_python
- 2022-06-25 基于Python實現(xiàn)五子棋游戲_python
- 2021-12-06 Redis限流的幾種實現(xiàn)_Redis
- 2023-02-02 一文教你利用Python制作一個生日提醒_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支