Recently I’ve been struggling to find a proper tutorial that explains how to link/integrate sqlite in linux c++ applications. Coming from a Windows background, with all the automation provided by Visual C++, it’s hard to go back to the old school manual compilation and linking. After spending hours looking for “the equivalent of sqlite3.dll for Linux” I managed to make it work and decided to share my knowledge.
I will provide a coincise step-by-step tutorial with comments on how to use it and execute a couple of simple commands. The usage of SQLite commands in c++ is beyond the scope of this tutorial, as there are already may resources out there which are really helpful.
Let’s start!
- The first step is installing sqlite tools (optional) and development libraries on your system.
If you’re running Ubuntu or ubuntu-based distribution, you can run the command:
sudo apt-get install sqlite3 libsqlite3-dev
instead if you’re running Fedora/Centos or any Red Hat Enterprise distro
sudo yum install sqlite
to install the tools, and the development toolkit should be included by default. - We’re now ready to create the database. Run on you terminal
sqlite3
and in the sqlite console.open --new databaseName.db
(after that enter.exit
to exit the utility). Now the database file should appear in the the directory of the terminal where you ran the command. - With the database file, we are finally ready to test it in C++. Use your favourite code editor to create the file main.cpp in the same folder as the database file and enter the following code:
#include "sqlite3.h" #include <iostream> using namespace std; int main() { sqlite3* db; int res = sqlite3_open("databaseName.db", &db); if(res) //database failed to open cout << "Database failed to open" << endl; else { //your database code here } sqlite3_close(db); }
You can find a good and complete tutorial on how to query or modify the database at this address.
- We’re now ready to create an executable. I use g++ compiler for this task, and the default linker.
Rung++ main.cpp -l sqlite3 -o main
to compile and./main
to execute your code.
You’re now ready to add the code to your application and integrate other functionalities.