Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SQLite – C/C++


May 16, 2021 SQLite


Table of contents


SQLite - C/C++

Installation

Before we can use SQLite in the C/C?program, we need to make sure that the SQLite library is already on the machine. You can review the SQLite installation section to learn about the installation process.

The C/C?interface API

The following are the important C?C?/SQLite interface programs to meet your needs for using the SQLite database in C/C?programs. If you need more details, check out the official SQLite documentation.

Serial number API & Description
1 sqlite3_open(const char *filename, sqlite3 **ppDb)

This routine opens a connection to the SQLite database file, returns a database connection object for other SQLite programs.

if filename The parameters are null or ': memory:', SQLite3_Open () will create a memory database in the RAM, which will only continue within the effective time of the session.

If the file name filename is not null, SQLITE3_Open () will use this parameter value to try to open the database file.If the file does not exist, SQLite3_Open () will create a new database file that named the name and open.

2 sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)

This routine provides a shortcut to execute the SQL command, and the SQL command is provided by the SQL parameter, which can be composed of a plurality of SQL commands.

Here, the first parameter sqlite3 Is the open database object, sqlite_callback Is a callback, data As its first parameter, Errmsg will be returned to acquire any errors generated by the program.

SQLITE3_EXEC () program resolution and execution sql Each command given by the parameter until the string ends or has an error.

3 sqlite3_close(sqlite3*)

This routine is turned off before calling a database connection.All statements associated with connection should be done before the connection is closed.

If there is still a query is not completed, SQLite3_close () will return SQLITE_BUSY to disable closing error messages.

Connect to the database

The following C snipp is a snipper that shows how to connect to an existing database. If the database does not exist, it is created and a database object is returned.

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

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;

   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");
   }
   sqlite3_close(db);
}

Now let's compile and run the program above, create our database test in the current directory.db. You can change the path as needed.

$gcc test.c -l sqlite3
$./a.out
Opened database successfully

If you want to use the source code for C+, you can compile the code as follows:

$g++ test.c -l sqlite3

Here, link our program to the sqlite3 library to provide the necessary functions to the C program. This creates a database file test in your directory and .db you get the following results:

-rwxr-xr-x. 1 root root 7383 May  8 02:06 a.out
-rw-r--r--. 1 root root  323 May  8 02:05 test.c
-rw-r--r--. 1 root root    0 May  8 02:06 test.db

Create a table

The following C snippet will be used to create a table in a previously created database:

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

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i&lt;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;
   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(stdout, "Opened database successfully\n");
   }

   /* Create SQL statement */
   sql = "CREATE TABLE COMPANY("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "NAME           TEXT    NOT NULL," \
         "AGE            INT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "SALARY         REAL );";

   /* 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, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When the above program is compiled and executed, it creates a COMPANY table .db the test file, and the final list of files looks like this:

-rwxr-xr-x. 1 root root 9567 May  8 02:31 a.out
-rw-r--r--. 1 root root 1207 May  8 02:31 test.c
-rw-r--r--. 1 root root 3072 May  8 02:31 test.db

INSERT operation

The following C snippet shows how to create records in the COMPANY table created above:

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

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i&lt;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;
   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;
}

When the above program is compiled and executed, it creates a given record in the COMPANY table and displays the following two lines:

Opened database successfully
Records created successfully

SELECT operation

Before we begin to explain getting instances of records, let's look at some of the details of the next callback function, which will be used in our instances. T his callback provides a way to get results from select statements. It states the following:

typedef int (*sqlite3_callback)(
void*,    /* Data provided in the 4th argument of sqlite3_exec() */
int,      /* The number of columns in row */
char**,   /* An array of strings representing fields in the row */
char**    /* An array of strings representing column names */
);

If the callback above is the third argument in the sqlite_exec() program, SQLite calls this callback function for each record processed in each SELECT statement executed within the SQL parameter.

The following C snippet shows how to get and display records from the COMPANY table you created earlier:

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

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   for(i=0; i&lt;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;
   char *sql;
   const char* data = "Callback function called";

   /* 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 = "SELECT * from COMPANY";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When the above program is compiled and executed, it produces the following results:

Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0

Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0

Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0

Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

UPDATE operation

The following C snippet shows how to use the UPDATE statement to update any record, and then get and display the updated record from the COMPANY table:

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

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   for(i=0; i&lt;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;
   char *sql;
   const char* data = "Callback function called";

   /* 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 merged SQL statement */
   sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \
         "SELECT * from COMPANY";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When the above program is compiled and executed, it produces the following results:

Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0

Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0

Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0

Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

DELETE operation

The following C snippet shows how to use the DELETE statement to delete any records, and then get and display the remaining records from the COMPANY table:

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

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   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;    char *sql;    const char* data = "Callback function called";     /* 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 merged SQL statement */    sql = "DELETE from COMPANY where ID=2; " \          "SELECT * from COMPANY";     /* Execute SQL statement */    rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);    if( rc != SQLITE_OK ){       fprintf(stderr, "SQL error: %s\n", zErrMsg);       sqlite3_free(zErrMsg);    }else{       fprintf(stdout, "Operation done successfully\n");    }    sqlite3_close(db);    return 0; } 

When the above program is compiled and executed, it produces the following results:

Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0

Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0

Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully