上下文管理器 with。。as

(1)文件读取--上下文管理器  with open(filename,'w') as f :

class MyOpen:
def __init__(self, filename, mode, encoding='utf-8'):
self.filename = filename
self.mode = mode
self.encoding = encoding

def __enter__(self):
self.f = open(self.filename, self.mode, encoding=self.encoding)
return self.f

def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close()


with MyOpen('add.yml', 'r') as f:
print(f.read())

(2) mysql数据表读取 --上下文管理器:


from mysql import connector


class MySql:
def __init__(self, host, user, password, database, port):
self.host = host
self.user = user
self.password = password
self.database = database
self.port = port

def __enter__(self):
self.conn = connector.connect(host=self.host, user=self.user, password=self.password,
database=self.database, port=self.port)
self.cur = self.conn.cursor()
return self.cur

def __exit__(self, exc_type, exc_val, exc_tb):
self.cur.close()
self.conn.close()


with MySql('127.0.0.1', 'root', 'password', 'db', '3306') as cursor:
cursor.execute('select * from projects')
print(cursor.fetchall())
posted @ 2022-04-22 21:46  狒狒桑  阅读(21)  评论(0编辑  收藏  举报