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?