Databases with SQLite · 15 / 15 Exercise Hard

Integrity constraints

Objective

Create a Python program that lets the database itself reject invalid data through constraints, catching sqlite3.IntegrityError. Use an in-memory database with the sqlite3 module (sqlite3.connect(":memory:")).

Instructions

  • Create users with email TEXT PRIMARY KEY (primary key: it cannot repeat) and age INTEGER CHECK (age >= 18) (adults only).
  • Read n lines with email age. Try to insert each user inside with con:.
  • If it is inserted, show Registered: email; if sqlite3.IntegrityError is raised (repeated email or age under 18) show Rejected: email.
  • At the end show Users: k and the stored emails, one per line and sorted.
Input
4
a@x.com 20
b@x.com 17
a@x.com 30
c@x.com 18
Output
Registered: a@x.com
Rejected: b@x.com
Rejected: a@x.com
Registered: c@x.com
Users: 2
a@x.com
c@x.com

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise