假设您有一个非常简单的表,名为User
看起来像这样:
╔════╦══════════╗
║ ID ║ Name ║
╟────╫──────────╢
║ 1 ║ Slvrfn ║
║ 2 ║ Sean ║
║ 3 ║ Drew ║
║ 4 ║ mah ║
╚════╩══════════╝
然后你打电话sqlite3_exec
像这样(参数详细描述在文档中 https://www.sqlite.org/c3ref/exec.html):
/* Error handling omitted for brevity */
sqlite3_exec(db, "SELECT * FROM User", my_special_callback, NULL, NULL);
SQLite 将执行传递的 SQL 语句,并且对于它找到的每个结果行,它将调用my_special_callback
。所以以我们的例子为例User
table, my_special_callback
将被调用 4 次。那么让我们创建my_special_callback
:
/*
* Arguments:
*
* unused - Ignored in this case, see the documentation for sqlite3_exec
* count - The number of columns in the result set
* data - The row's data
* columns - The column names
*/
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;
}
鉴于我们的示例表和数据,输出将如下所示:
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
现在如何使其有用,这就是第四个参数的地方sqlite3_exec
进来。来自文档:
sqlite3_exec() 的第四个参数被转发到第一个
每个回调调用的参数。
假设我们要运行 SQL 并构建所有用户姓名的链接列表。我们需要做的第一件事是改变我们的调用方式sqlite3_exec
:
/* Create my fictional linked list */
struct my_linked_list *head = my_linked_list_alloc();
/*
* Pass a pointer to my list as the 4th argument to sqlite3_exec. Error
* handling omitted for brevity
*/
sqlite3_exec(db, "SELECT * FROM User", my_special_callback, head, NULL);
/* My list is now built, I can do stuff with it... */
my_linked_list_traverse(head, /* ... Stuff ... */);
并修改my_special_callback
使用它
/*
* Arguments:
*
* list - Pointer to a linked list of names
* count - The number of columns in the result set
* data - The row's data
* columns - The column names
*/
static int my_special_callback(void *list, int count, char **data, char **columns)
{
struct my_linked_list *head = list;
/*
* We know that the value from the Name column is in the second slot
* of the data array.
*/
my_linked_list_append(head, data[1]);
return 0;
}
现在,如果您要使用callback
您将其包含在您的问题中,您可以这样称呼它:
/*
* Pass the table name as the 4th argument to sqlite3_exec. Error
* handling omitted for brevity
*/
sqlite3_exec(db, "SELECT * FROM User", callback, "User", NULL);
输出将是:
User:
ID = 1
Name = Slvrfn
User:
ID = 2
Name = Sean
... etc ...
(除了User:
部分将打印到 stderr 而不是 stdout)
希望这可以帮助您解决问题。如果您还有不明白的地方,请告诉我。