20 Sat
[HEAD FIRST PYTHON] 9๊ฐ ์ปจํ
์คํธ ๊ด๋ฆฌ ํ๋กํ ์ฝ : ํ์ด์ฌ์ with๋ฌธ๊ณผ ์ฐ๊ฒฐํ๊ธฐ
๋ฉ์๋๋ก ์ปจํ
์คํธ ๊ด๋ฆฌํ๊ธฐ
def __init__(self, config: dict):
"""Add the database configuration parameters to the object.
This class expects a single dictionary argument which needs to assign
the appropriate values to (at least) the following keys:
host - the IP address of the host running MySQL/MariaDB.
user - the MySQL/MariaDB username to use.
password - the user's password.
database - the name of the database to use.
For more options, refer to the mysql-connector-python documentation.
"""
self.configuration = config
def __enter__(self) -> 'cursor':
"""Connect to database and create a DB cursor.
Return the database cursor to the context manager.
"""
self.conn = mysql.connector.connect(**self.configuration)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_value, exc_traceback):
"""Destroy the cursor as well as the connection (after committing).
"""
self.conn.commit()
self.cursor.close()
self.conn.close()Last updated