Skip to content

Incorrect explanation and usage in assignment8 #122

@chillymosh

Description

@chillymosh

In https://github.com/Code-the-Dream-School/python-essentials-v1/blob/main/mentor-guidebook/assignment-solution-examples/assignment8/advanced_sql.py it states:

  # The with statement is helpful, because it ensures that the connection
  # is closed at the end, even if an exception occurs
  with sqlite3.connect("../db/lesson.db") as conn:
      conn.execute("PRAGMA foreign_keys = 1")  

This is incorrect. https://docs.python.org/3/library/sqlite3.html#sqlite3-connection-context-manager

A Connection object can be used as a context manager that automatically commits or rolls back open transactions when leaving the body of the context manager. If the body of the with statement finishes without exceptions, the transaction is committed. If this commit fails, or if the body of the with statement raises an uncaught exception, the transaction is rolled back. If autocommit is False, a new transaction is implicitly opened after committing or rolling back.

If there is no open transaction upon leaving the body of the with statement, or if autocommit is True, the context manager does nothing.

Note The context manager neither implicitly opens a new transaction nor closes the connection. If you need a closing context manager, consider using contextlib.closing().

Example:

import sqlite3

with sqlite3.connect("../db/magazines.db") as conn:
    ...

print(conn.execute("SELECT 1").fetchone())
conn.close()
print(conn.execute("SELECT 1").fetchone())


> (1,)
> sqlite3.ProgrammingError: Cannot operate on a closed database.

There may be other files with the same practice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions