Tuesday, October 29, 2013

Integrate SQLite with Visual C++

MySQL, SQL Server and Oracle are the generally used database systems. But with the arrival of embedded and mobile devices, SQLite has become very useful. When you are doing a project using C or C++, SQLite will be the most suitable option according to the scale of your project. SQLite is a light weight database system. When I tried to integrate SQLite into my Visual C++ project, I realize that there is no proper documentation that make the developer's life easier. So I am going to explain my experience.

First download SQLite from the developer's web site. You have to download 
  • sqlite-shell-win32-x86-3080100.zip  
  • sqlite-dll-win32-x86-3080100.zip from the Precompiled Binaries for Windows section. 
  • And sqlite-amalgamation-3080100.zip file from the same site.

Then extract all the zip files to one folder. Lets assume that folder is "C:\SQLite". 

Now add the path of that folder into the PATH variable of your computer.(Same procedure as you do it in Java jdk.)

Now open the Visual Studio Command Prompt which I mentioned in this post. Then type below command and press enter. This will create sqlite3 library file.
lib /DEF:"C:\SQLite\sqlite3.def" /OUT:"C:\SQLite\sqlite3.lib"

Now after that open your Visual C++ project using Visual Studio IDE. Then write click your project and goto Properties.

Then following window will appear.

Now go to the C/C++ section from the left tab. When selecting that, the right tab will change. Now add the path of your SQLite folder into the "Additional Include Directories".

Then go to the General section of the Linker from the left tab.(Linker -> General). Now again add the same path to the "Additional Library Directories".

Finally go to the Input sub section of the Linker (Linker -> Input) and add "sqlite3.lib" in to the Additional Dependencies. Then press OK.

Now you are done and you can do your coding.

First include the sqlite3.h header file using #include <sqlite3.h> code.

Then do your coding. Below code is extracted from this tutorial. It just opens and connects to a new database.

#include <stdio.h>
#include <sqlite3.h>

int main(int args, char* argv[]){
    sqlite *db;
    char *zErrMsg = 0;
    int rc;  
    rc = sqlite3_open("database_1.db", &db);
      printf("Can't open databse: %s\n", sqlite3_errmsg(db));
      printf("Opened database successfully\n");

Happy Coding! :)

No comments:

Post a Comment