20 Sat
[HEAD FIRST PYTHON] 9๊ฐ ์ปจํ
์คํธ ๊ด๋ฆฌ ํ๋กํ ์ฝ : ํ์ด์ฌ์ with๋ฌธ๊ณผ ์ฐ๊ฒฐํ๊ธฐ
7์ฅ์์๋ ์ปจํ ์คํธ ๊ด๋ฆฌ ํ๋กํ ์ฝ์ ์ ์ฉํ with๋ฌธ์ ์ด์ฉํ๋ ๊ฒ์ด ์ข๋ค๋ ๊ฒฐ๋ก ์ ์ป์๊ณ 8์ฅ์์๋ ํด๋์ค๋ฅผ ๋ฐฐ์ ๋ค. 9์ฅ์์๋ ํด๋์ค์ ์ปจํ ์คํธ ๊ด๋ฆฌ์๋ฅผ ํตํด ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฝ๋๋ฅผ ๊ณต์ ํ๋ ์์ ์ ์์ํ ๊ฒ์
๋ฉ์๋๋ก ์ปจํ
์คํธ ๊ด๋ฆฌํ๊ธฐ
์ปจํ
์คํธ ๊ด๋ฆฌ ํ๋กํ ์ฝ์ ์ค์ํ๋ ๋ชจ๋ ํด๋์ค๋ __enter__
์ __exit__
๋ ๊ฐ์ ์์ ๋ฉ์๋๋ฅผ ๋ฐ๋์ ์ ์ํด์ผ ํ๋ค.
enter๋ ์ค์ ์ ๋ด๋นํ๋ค.
๊ฐ์ฒด๊ฐ with๋ฌธ์ ์ค์ํธ๋ฅผ ์์ํ๊ธฐ ์ ์ enter ๋ฉ์๋๋ฅผ ๋จผ์ ํธ์ถํ๋ค. ํ๋กํ ์ฝ์ enter๊ฐ with๋ฌธ์ ๋ฐํ๊ฐ์ ์ ๊ณตํ ์ ์์์ ๋ช ์ํ๋ค.
exit๋ ๋ง๋ฌด๋ฆฌ๋ฅผ ๋ด๋นํ๋ค.
๊ฐ์ฒด๊ฐ with๋ฌธ์ ์ค์ํธ๋ฅผ ๋ง๋ฌด๋ฆฌ ํ๊ธฐ์ ์ exit ๋ฉ์๋๋ฅผ ํธ์ถํ๋ค.
์์ธ ๋ฐ์ ๋ฑ์ผ๋ก ์ธํด ์ ์์ ์ผ๋ก ๋์ํ์ง ์์ ๊ฒฝ์ฐ๋ฅผ ๋๋นํด exit ๋ฉ์๋๋ฅผ ๊ตฌํํด์ผ ํ๋ค.
init์ ์ด๊ธฐํ๋ฅผ ๋ด๋นํ๋ค.
enter ๋ฉ์๋๊ฐ ํธ์ถ๋๊ธฐ ์ ์ ๋จผ์ ์คํ๋๋ค.
์ปจํ ์คํธ ๊ด๋ฆฌ์๋ init์ ์ ์ํ ํ์๋ ์์ง๋ง ์ค์ ์ฝ๋์ ์ด๊ธฐํ ์ฝ๋๋ฅผ ๋ถ๋ฆฌํ ์ ์์ผ๋ฏ๋ก ์ ์ํ๋ฉด ์ ์ฉํ๋ค.
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()
1 : initํ๋ ๊ณผ์
14 : dbconfig๋ฅผ self.configuration์ผ๋ก ์ด๊ธฐํํ๋ค.
16 : enter์ ๋ฐํ๊ฐ์ผ๋ก cursor๋ผ๋ ๊ฒ์ ์๋ ค์ฃผ๊ธฐ ์ํด ์ด๋ ธํ ์ด์ ์ ์ถ๊ฐ ํ๋ค.
21 : dbconfig๊ฐ ์๋๋ผ self.configuration์ ์จ์ค๋ค.
23 : cursor๋ฅผ ๋ฐํ
25 : ์ธ์๊ฐ์ ๋ํด์๋ ์ถํ์ ์ค๋ช
Last updated
Was this helpful?