This example will demonstrate how you could use the C/C++ interface to execute SQL statement in SQLite. If you are new to C/C++ & SQLite, it is advisable that you read my previous article on Establish a connection to SQLite database using C++, so that you have a better understanding what how and what to do in this demonstration. To start the demo, let’s create a new callback function. The callback function is triggered once there is data ready to display. This usually happen when the select statement being executed.
1
2
3
4
5
6
7
8
9
10
11
// This is the callback function to display the select data in the table
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;
}
In the main function, right after the database being open successfully and before it’s close, we need to insert the following codes into the main function so that our mission in this demonstration can be accomplished.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  // ..
  // .. after open database
  // ..

  const char *pSQL[6];

  // Create a new myTable in database
  pSQL[0] = "create table myTable (FirstName varchar(30), LastName varchar(30), Age smallint)";

  // Insert first data item into myTable
  pSQL[1] = "insert into myTable (FirstName, LastName, Age) values ('Woody', 'Alan', 45)";
 
  // Insert second data item into myTable
  pSQL[2] = "insert into myTable (FirstName, LastName, Age) values ('Micheal', 'Bay', 38)";

  // Select all data in myTable
  pSQL[3] = "select * from myTable";
 
  // Remove all data in myTable
  pSQL[4] = "delete from myTable";

  // Drop the table from database
  pSQL[5] = "drop table myTable";

  // execute all the sql statements
  for(int i = 0; i < 6; i++)
  {
    rc = sqlite3_exec(db, pSQL[i], callback, 0, &zErrMsg);
    if( rc!=SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      break; // break the loop if error occur
    }
  }

  // ..
  // .. before close database
  // ..
If you compile and run the appliction now, you should see a similar screen shot as shown.
C++ SQLite Example

C++ SQLite Example

Download sample source code: C++ SQLite Example