C++ with SQLite3: Part 1: Downloading and Compiling

C++ with SQLite3

SQLite3 is the most-used SQL implementation in the world. It is a self-contained C library included in everything from portable devices to web browsers.

Note: This tutorial assumes some familiarity with using the command-line to create and compile files. It was written using a MacOS X machine and also assumes easy access to g++. (For Windows systems, consider using MinGW.)


The SQLite3 library can easily be found on its website. Find and download the “amalgamation” file that contains all of the source code.

Extract the contents of the ZIP file into a folder. Using a command-line, enter the same folder.

touch test.cpp

Create a new file called “test.cpp” (or your preference).

Open this file in the editor of choice and enter the following code.

#include <iostream>
#include <sqlite3.h>
using namespace std;
int main()
// Pointer to SQLite connection
sqlite3* db;
// Save the connection result
int exit = 0;
exit = sqlite3_open("example.db", &db);
// Test if there was an error
if (exit) {
cout << "DB Open Error: " << sqlite3_errmsg(db) << endl;
} else {
cout << "Opened Database Successfully!" << endl;
// Close the connection
return (0);
view raw test.cpp hosted with ❤ by GitHub


SQLite3 is an external library. To compile it correctly, it must also be linked to the project. For that, use the “-l” (linker) option for g++.

g++ test.cpp -l sqlite3

If the compilation worked, nothing will be shown. To see the result, run the default output file for g++, “a.out.”


Assuming everything worked correctly, the following message will appear.

Opened Database Successfully!

What about the “example.db” file?

SQLite3 will attempt to open a file given to it. If the file cannot be found, it creates it.

Checking the contents of the folder will show that the file “example.db” now exists. SQLite created it.