Opening a SQLite database with python

This short article show you how to connect to a SQLite database using python. We will use the with keyword in order to avoid having to close the database.

In order to connect to the database, we will have to import sqlite3

import sqlite3
from sqlite3 import Error

In python the with keyword is used when working with unmanaged resources (like file streams).

The python documentation tells us that :

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
        with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has enter() and exit() methods).

db_file = ".\\mydatabase.db"
try :
    with sqlite3.connect(db_file) as conn:
        print("Connected to the database")
        #your code here
except Error as e:
    print(e)
Connected to the database