【发布时间】:2021-11-04 02:58:51
【问题描述】:
我写了一个类来从 MySQL 数据库中收集数据。
当我使用with 时,我不明白如何使用__enter__ 和__exit__ 方法。
更具体地说,我不明白:
-
我应该在哪里返回
self.raws = self.crouser.execute(self.que)实际上是数据库中的数据。 -
直到连接打开?
-
在这个具体问题中如何使用
with方法?
我的代码:
import mysql.connector
class tak:
def __init__(self,host1, user1, password1, db1,aat, que1):
self.host = host1
self.user = user1
self.password = password1
self.database = db1
self.auth_plugin = aat
self.que = que1
def co(self):
try:
self.my = mysql.connector.connect(
host = self.host,
user = self.user,
password = self.password,
database = self.database,
auth_plugin = self.auth_plugin,
charset = 'utf8'
)
except mysql.connector.errors as err :
print(f'{err}')
self.crouser = self.my.cursor()
self.raws = self.crouser.execute(self.que)
self.crouser.fetchall()
def __enter__(self):
return
def __exit__(self, exc_type, exc_val, exc_tb):
self
with tak(host1="localhost",
user1="root",
password1="1234",
db1="local_db",
aat='mysql_native_password',
que1='select * from nand').co() as log:
print(log)
【问题讨论】:
标签: python mysql-python with-statement python-class