How to Use SQLite in Visual Studio 2017
Step 1: Install VS2017
I assume you know how to install visual studio 2017. so I ingore this step here.
Step 2: Download SQLite component
Download sqlite.h、sqlite.dll、sqlite.def files from SQLite official website.
- Download the source code. There is the sqlite.h file inside the source code.
2. Download the sqlite.dll and sqlite.def according to your system.(my system is x64)
Step 3: Create a lib file
Find the lib.exe executable in Vistual Studio on your system.
In my case, the file path is “C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\lib.exe”.
Then, copy sqlite.def file to this folder and run the below command.
lib.exe /machine:x64 /def/sqlite3.def
After doing that. You will get a *.lib file.
Note:
- If it fails to run the above command, you can try to copy the x64 folder outside of your Vistual Studio path and run the command again.
- If there is an error likes service error, you need to use administrator privilege to run the command.
Step 4: Add lib file to Vistual Studio
- Open Vistual Studio 2017 and create a project.
- Put sqlite.h and sqlite.dll files into project folder(the same path with source code)
- Browser to Project Properties->connector-> input->additional dependency and include *.lib(we created it in step 3) path.
Now, we can use SQLite in Vistual Studio 2017.
Step 5: Test
Below code is used to test if we can use SQLite in Vistual studio.
#include "pch.h" #include "sqlite3.h" #include <iostream> #include <stdio.h> #include <stdlib.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for (i = 0; i < argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; /* Open database */ rc = sqlite3_open("test.db", db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, zErrMsg); if(rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Records created successfully\n"); } sqlite3_close(db); return 0; }
Note:
You can download a Database Browser to check the result or you can read the data from database after you have written it.
Related article:
SQLite-How to Insert Multiple Rows At a Time In C