Creating a simple database with SQLite in C
A C program often needs to remember more than its current process: customers, jobs, preferences or audit events. Storing that information in fixed arrays becomes fragile as soon as the number of records or the relationships between them change. A small embedded relational engine can provide durable storage, queries and constraints while remaining a library linked directly into the executable.
SQLite offers that model with no separate database server to install or administer. Its file-backed design suits desktop utilities, automation programs and small internal tools. The same compact approach that suited software makers in the mid-2000s remains effective for developers building focused command-line applications today.
Why an embedded database fits small C programs
SQLite is an in-process relational database engine. It reads and writes a normal file, exposes a C API and lets the operating system handle file access. There is no daemon, network port or service account to configure, so a single binary can contain the complete persistence layer.
The engine organises records into rows and uses a declared schema to preserve types, primary keys and relationships. SQL gives the application a stable way to search, aggregate and update data, while prepared statements reuse compiled queries and bind values separately from SQL text.
Its limits matter. SQLite permits multiple readers but serialises writers, so it works best when one process owns the data or several processes take turns. A busy network service with many simultaneous editors usually belongs on a client-server database such as PostgreSQL or MySQL.
Preparing the build and defining the data model
A C build needs the SQLite header and library. On Debian or Ubuntu, libsqlite3-dev provides them; on macOS, Homebrew or the system package may be suitable. A typical command compiles with strict warnings and asks pkg-config for the correct link flags.
cc records.c -o records \
-Wall -Wextra -pedantic \
$(pkg-config --cflags --libs sqlite3)
Start with a small data model. An appointment or customer record might have an integer identifier, a required name, an optional email address and a creation time. Declare those fields in SQL rather than inventing parallel C structures, and let the engine enforce uniqueness and required values.
Keep the first schema narrow. Add an index only for a field commonly searched or joined, because every index consumes disk space and slows writes slightly. The schema should describe the business meaning of each column, not mirror a temporary screen layout.
Opening the database without losing control
Open the file with sqlite3_open_v2, requesting read and write access plus creation only when appropriate. The explicit flags prevent accidental creation, while sqlite3_busy_timeout gives another process a short grace period before returning a lock error.
sqlite3 *db = NULL;
int rc = sqlite3_open_v2("records.db", &db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (rc != SQLITE_OK) {
fprintf(stderr, "open failed: %s\n", sqlite3_errstr(rc));
sqlite3_close(db);
return 1;
}
sqlite3_busy_timeout(db, 5000);
Treat every return code as part of normal control flow. Prepare, bind, step and finalise each have distinct failure modes, and sqlite3_errmsg supplies a useful explanation. Close the connection on every exit path, including parse errors, so temporary statements and file handles are released.
Choose the filename deliberately. A relative path places the database in the current working directory, which can surprise a desktop launch. Store operational data under a per-user application directory, and keep the executable directory read-only in packaged deployments.
Adding and reading records safely
Use prepared statements for every value that can come from outside the program. The client structure described earlier has a name and email field, so an insert needs two placeholders and two bound values. This keeps user-entered text out of the SQL syntax and removes the usual SQL injection risk.
sqlite3_stmt *stmt = NULL;
sqlite3_prepare_v2(db,
"INSERT INTO clients(name,email) VALUES(?,?)",
-1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, name, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, email, -1, SQLITE_TRANSIENT);
int rc = sqlite3_step(stmt);
sqlite3_finalize(stmt);
SQLITE_TRANSIENT instructs SQLite to copy a bound string, so the C variable may safely change or leave scope after binding. The application should still check the result of preparing, binding and stepping rather than assuming that an empty field, duplicate address or unavailable disk will not cause failure.
Read a row at a time by stepping through a prepared SELECT. sqlite3_step returns SQLITE_ROW while data is available and SQLITE_DONE after the final row. Treat a NULL column explicitly, and copy text if it must outlive the next call to sqlite3_step.
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
const unsigned char *name =
sqlite3_column_text(stmt, 1);
printf("%s\n", name ? (const char *)name : "(none)");
}
sqlite3_finalize(stmt);
Updates and deletes use the same binding pattern. A change statement should normally affect one row; check sqlite3_changes when that matters. After each operation, reset or finalise the statement, and never reuse it after finalisation.
The practical choices for a local C utility compare like this:
| Approach | Setup and footprint | Concurrent writing | Strongest use |
|---|---|---|---|
| SQLite library | Embedded in one binary with a local file | One writer at a time; multiple readers | Desktop utilities and modest shared data |
| CSV or flat file | Very small and easy to inspect | No database locking | Exports, logs and tiny fixed datasets |
| PostgreSQL or MySQL | Separate server plus client libraries | Designed for many simultaneous writers | Multi-user networked services |
Defining the schema and protecting changes
Create the relational structure with a schema statement. This example lets SQLite generate identifiers and stores the timestamp in a standard UTC text form. Execute the statement through sqlite3_exec, or prepare it when you need bindings and precise error handling.
const char *sql =
"CREATE TABLE IF NOT EXISTS clients ("
" id INTEGER PRIMARY KEY,"
" name TEXT NOT NULL,"
" email TEXT UNIQUE,"
" created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"
");";
Group related writes in a transaction. BEGIN IMMEDIATE acquires the write lock early, COMMIT makes all changes durable together, and ROLLBACK discards them if a later operation fails. This atomicity prevents a payment record from surviving without its matching invoice.
if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK)
return 1;
/* Perform the related writes, then commit or roll back. */
Constraints are part of the safety model. Use foreign keys for relationships, NOT NULL for mandatory values and UNIQUE for identifiers such as email addresses. Enable foreign-key enforcement with PRAGMA foreign_keys = ON on every connection; it is not a persistent schema setting.
Track structural changes with PRAGMA user_version. Increment that value after each migration and run the matching migration when the recorded version is older than the program expects. Keep a tested backup before altering a production file, since SQLite cannot express every desired ALTER TABLE operation directly.
Australian data, privacy and everyday deployment
Australian sole traders give the design a useful scale. Neighbourhood businesses often combine counter service, phone bookings and takeaway orders. A barber in Melbourne, a photographer in Sydney or a tutor in Brisbane may need client records but not a database cluster. A local executable can keep those records on one Windows notebook or Mac.
Local business software makes interoperability practical. Many small organisations use Xero or MYOB rather than bespoke accounting tools, so a dependable CSV export can be more valuable than an elaborate reporting layer. The embedded database remains the working store, not necessarily the final destination for financial or customer information.
Time handling matters for teams spread across Australia. Store timestamps in UTC, then display them in the relevant local zone; daylight-saving changes make a fixed offset unreliable. For appointments, also retain the intended local date and time so a later timezone correction cannot shift the booking.
Privacy duties depend on the records and the organisation. Generally, private-sector organisations with annual turnover above $3 million are covered by the Privacy Act 1988, as are government entities and certain trades regardless of turnover. Many small businesses are exempt, but exceptions apply. The 2024 amendments expanded the regime, while the Notifiable Data Breaches scheme requires covered entities to assess eligible information and notify affected people when the statutory test is met.
Health and service data can trigger additional state or territory rules. The Health Records Act 2001 in Victoria and the My Health Records Act 2012 federally affect relevant health information. A program storing such data needs restricted access, sensible retention and accurate breach procedures, with legal advice used where the boundary remains unclear.
Hardening, testing and shipping the program
Build with warnings enabled and test unusual paths as carefully as successful ones. Run the program under AddressSanitizer or Valgrind, feed it empty fields and oversized values, and force a database-open failure. Confirm that statements are finalised and the connection closes whenever an operation returns an error.
Protect the file as operational data. Restrict permissions to the account that needs it, avoid storing data where users cannot write, and test recovery from a copied backup. Write-Ahead Logging can improve reader and writer coexistence, but it creates companion files and still permits only one writer at a time.
Release the program with a known schema version, a plain-English description of each stored field and an export or migration path. The completed utility remains compact, portable and dependable: a local file for persistence, prepared C calls for safe access, and transactions for consistency.