使用上下文管理器语句连接非常有用,如下所示:
with psycopg2.connect(**dns) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as curs:
...如何定义使用上下文管理器处理数据库的类?
class DBConn:
def __init__(self, dns):
self.conn = psycopg2.connect(**dns)
self.curs = self.conn.cursor()
def __enter__(self):
pass
def __exit__(self):
pass发布于 2022-06-15 11:06:30
拿到了..。
class DBConn:
def __init__(self, dns):
self.connection = psycopg2.connect(**dns)
def __enter__(self):
return self.connection.cursor()
def __exit__(self, exc_type, exc_value, traceback):
self.connection.commit()
self.connection.close()https://stackoverflow.com/questions/72628457
复制相似问题