Suppose you have a very simple table called User , which looks something like this:
╔════╦═════════╗
║ ID ║ Name ║
╟────╫──────────╢
║ 1 ║ Slvrfn ║
║ 2 ║ Sean ║
║ 3 ║ Drew ║
║ 4 ║ mah ║
╚════╩═════════╝
And you call sqlite3_exec as follows (the arguments are described in detail in the documentation ):
sqlite3_exec(db, "SELECT * FROM User", my_special_callback, NULL, NULL);
SQLite will execute the passed SQL statement, and for each row of results found, it will call my_special_callback . So, in our User table example, my_special_callback will be called 4 times. So create my_special_callback :
static int my_special_callback(void *unused, int count, char **data, char **columns) { int idx; printf("There are %d column(s)\n", count); for (idx = 0; idx < count; idx++) { printf("The data in column \"%s\" is: %s\n", columns[idx], data[idx]); } printf("\n"); return 0; }
Given our sample table and data, the result will look like this:
There are 2 column (s)
The data in column "ID" is: 1
The data in column "Name" is: Slvrfn
There are 2 column (s)
The data in column "ID" is: 2
The data in column "Name" is: Sean
There are 2 column (s)
The data in column "ID" is: 3
The data in column "Name" is: Drew
There are 2 column (s)
The data in column "ID" is: 4
The data in column "Name" is: mah
Now, how to do this is where the 4th argument to sqlite3_exec . From the documentation:
The 4th argument of sqlite3_exec () is passed up to the 1st argument of each callback call.
So, let's say that we want to run our SQL and build a linked list of the names of all our users. The first thing we need to do is change the way we call sqlite3_exec :
struct my_linked_list *head = my_linked_list_alloc(); sqlite3_exec(db, "SELECT * FROM User", my_special_callback, head, NULL); my_linked_list_traverse(head, );
And change my_special_callback to use it
static int my_special_callback(void *list, int count, char **data, char **columns) { struct my_linked_list *head = list; my_linked_list_append(head, data[1]); return 0; }
Now, if you used the callback that you included in your question, you would call it like this:
sqlite3_exec(db, "SELECT * FROM User", callback, "User", NULL);
The conclusion will be:
User:
ID = 1
Name = Slvrfn
User:
ID = 2
Name = Sean
... etc ...
(Except that the User: part will be printed in stderr instead of stdout)
Hope this helps you figure it out. Let me know if there is something you don’t understand.