Intermediate   Chapter 158 · 30 min read · Module 12: Python Database and APIs

Database Connections

Learning objectives
  • After this chapter you can open a connection to a file database and to an in-memory database.
  • You can explain the roles of the connection and the cursor.
  • You can close connections safely with try/finally or contextlib.closing.
  • You can use row_factory to read columns by name.
  • You can handle connection errors and describe how other databases are connected.

Before a program can read or write data, it needs a way to talk to the database. That link is called a connection. You open it at the start of the work, use it to send SQL, and close it when you are finished. Handling this link carefully is one of the most important habits in database programming.

In Python, the sqlite3 module makes connecting very simple. A single call to sqlite3.connect() opens a file, creating it if it does not exist yet. You can also ask for a database that lives only in memory, which is ideal for tests and experiments. Other databases such as PostgreSQL and MySQL use the same ideas, but they need an extra package and more connection details such as host, user and password.

In this chapter you will open and close connections, learn what a cursor is, read rows by column name, and see what happens when a connection fails. You will also learn the difference between closing a connection and committing a transaction, because many beginners mix them up.

Opening a connection

sqlite3.connect(path) returns a connection object. If path is a file name, SQLite opens that file and creates it when it is missing. If path is the special string ':memory:', SQLite makes a fresh database in RAM that disappears when the connection is closed. Each call to connect(':memory:') gives a separate, private database, so two in-memory connections never see each other's tables.

Connection: an object that represents an open link to one database; it sends SQL, controls transactions and must be closed when no longer needed
Example 1: file database versus memory database
import sqlite3, os
conn = sqlite3.connect('shop.db')
conn.execute('CREATE TABLE items (name TEXT)')
conn.execute('INSERT INTO items VALUES (?)', ('pen',))
conn.commit()
conn.close()
print(os.path.exists('shop.db'))

again = sqlite3.connect('shop.db')
print(again.execute('SELECT name FROM items').fetchall())
again.close()

m1 = sqlite3.connect(':memory:')
m2 = sqlite3.connect(':memory:')
m1.execute('CREATE TABLE t (x)')
try:
    m2.execute('SELECT * FROM t')
except sqlite3.OperationalError as e:
    print('m2 error:', e)
True [('pen',)] m2 error: no such table: t

The first part shows that data written to a file and committed is still there when you connect again later. The second part shows that two memory databases are separate worlds.

The cursor

A cursor is the object that runs a statement and holds its results. You can create one with conn.cursor(). The shortcut conn.execute(...) creates a cursor for you and returns it. Cursors let you fetch rows step by step, so a program can handle a big result without loading everything at once. You can loop over a cursor directly, or call fetchone, fetchmany(n) or fetchall.

Example 2: using a cursor
import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('CREATE TABLE nums (n INTEGER)')
cur.executemany('INSERT INTO nums VALUES (?)', [(i,) for i in range(1, 8)])
cur.execute('SELECT n FROM nums ORDER BY n')
print(cur.fetchone())
print(cur.fetchmany(3))
print(cur.fetchall())
print(cur.description[0][0])
conn.close()
(1,) [(2,), (3,), (4,)] [(5,), (6,), (7,)] n

Each fetch call continues where the last one stopped, so the three calls above return different parts of the same result. The description attribute lists the column names of the last query.

Closing safely

A connection holds resources, such as a file handle, and it can keep a file locked. You should always close it. The classic pattern is try / finally. A shorter way is contextlib.closing, which calls close() for you when the with block ends. Be careful: using the connection itself in a with statement does not close it. It only commits or rolls back the current transaction.

Example 3: closing with contextlib.closing
import sqlite3
from contextlib import closing

with closing(sqlite3.connect(':memory:')) as conn:
    conn.execute('CREATE TABLE t (x)')
    conn.execute('INSERT INTO t VALUES (1)')
    print(conn.execute('SELECT COUNT(*) FROM t').fetchone()[0])

try:
    conn.execute('SELECT 1')
except sqlite3.ProgrammingError as e:
    print('closed:', e)
1 closed: Cannot operate on a closed database.
Using with conn: is for transactions (commit or rollback). Using with closing(conn): is for closing. If you want both, nest them.

Reading columns by name

By default every row is a tuple, so you must remember that column 0 is the name and column 1 is the price. Setting conn.row_factory = sqlite3.Row makes each row behave like a read-only mapping as well as a tuple. You can write row['price'], and you can get all column names with row.keys(). This makes code easier to read and safer when columns are reordered.

Example 4: sqlite3.Row
import sqlite3
conn = sqlite3.connect(':memory:')
conn.row_factory = sqlite3.Row
conn.execute('CREATE TABLE people (name TEXT, age INTEGER)')
conn.execute('INSERT INTO people VALUES (?, ?)', ('Asha', 30))
row = conn.execute('SELECT name, age FROM people').fetchone()
print(row['name'], row['age'])
print(row[0], row.keys())
print(dict(row))
conn.close()
Asha 30 Asha ['name', 'age'] {'name': 'Asha', 'age': 30}

When connecting fails

Connections can fail. The folder may not exist, the file may be read-only, or another process may hold a lock. SQLite raises sqlite3.OperationalError in these cases. Catch it where you open the connection and show a helpful message instead of letting the program crash. Also remember that opening a connection to a path with a missing folder fails, because SQLite creates files but not directories.

Example 5: handling a failed connection
import sqlite3
try:
    conn = sqlite3.connect('no_such_folder/data.db')
except sqlite3.OperationalError as e:
    print('could not open:', e)
could not open: unable to open database file

Other databases

Server databases follow the same pattern: connect, get a cursor, execute, fetch, close. The difference is the connection details. You pass a host, port, database name, user and password, and you install a driver such as psycopg for PostgreSQL or mysql-connector-python for MySQL. Never write passwords in your source code. Read them from environment variables or a settings file. Most drivers follow the DB-API 2.0 standard, which is why the method names cursor, execute, fetchall, commit and close look the same everywhere. The placeholder style can differ, though: sqlite3 uses ? while many drivers use %s.

Example 6: connecting to PostgreSQL (needs a server and a package)
import os
import psycopg

conn = psycopg.connect(
    host='localhost',
    dbname='shop',
    user='app',
    password=os.environ['DB_PASSWORD'],
)
cur = conn.cursor()
cur.execute('SELECT 1')
print(cur.fetchone())
conn.close()
(1,)

Python syntax

Syntax
conn = sqlite3.connect('file.db')
Syntax
conn = sqlite3.connect(':memory:')
Syntax
with closing(sqlite3.connect('file.db')) as conn: ...
Syntax
conn.row_factory = sqlite3.Row

Real-world applications

  • Opening the application database when a web server starts.
  • Using an in-memory database for fast automated tests.
  • Reading a local data file shipped with a desktop tool.
  • Connecting a script to a company PostgreSQL or MySQL server for reports.

Common mistakes

Mistake: Never closing the connection.
Fix: Use try/finally or contextlib.closing so close() always runs.
Mistake: Thinking that with conn: closes the connection.
Fix: It only commits or rolls back. Use closing(conn) or call conn.close().
Mistake: Expecting two :memory: connections to share data.
Fix: Each in-memory connection has its own database. Reuse one connection or use a file.
Mistake: Putting passwords directly in the source code.
Fix: Read secrets from environment variables or a protected config file.
Mistake: Connecting to a path whose folder does not exist.
Fix: Create the folder first with os.makedirs or pathlib, then connect.

Important tips

  • Open the connection once and pass it to functions, instead of reconnecting for every query.
  • Use sqlite3.Row when you read many columns.
  • Print cursor.description to see column names while exploring.
  • Keep database paths in one constant or setting.

Key points summary

  • connect() opens a connection; close() releases it.
  • ':memory:' makes a private temporary database.
  • A cursor runs SQL and holds the results.
  • with conn: manages transactions, not closing.
  • Server databases need a driver package and login details.

Exam and interview points

  • Explain connection, cursor and transaction in one sentence each.
  • Know that ':memory:' databases are separate per connection.
  • Know that with conn: does not close the connection.
  • Name the DB-API methods shared by most drivers.

Quick revision

  • connect -> cursor -> execute -> fetch -> close.
  • Use closing() or try/finally to close.
  • row_factory = sqlite3.Row gives access by column name.
  • OperationalError means the database could not be used.

Frequently asked questions

Do I have to create the database file first?

No. sqlite3.connect creates the file if it is missing, but the folder must exist.

Is it a problem if I forget to close a connection?

For tiny scripts Python closes it when the program ends, but in long programs it can leak resources and keep files locked, so always close it.

What is the difference between a connection and a cursor?

The connection is the link to the database and handles transactions. A cursor is created from it to run statements and fetch rows.

Can many threads share one sqlite3 connection?

By default a connection may only be used in the thread that created it. Give each thread its own connection.

Practise this chapter

16 practice questions Take the chapter quiz

Related chapters