The callback mechanism of SQLite source program analysis

Source: Internet
Author: User
Tags sql error sqlite
1.SQL is very convenient to access the database, just simple three functions:
Sqlite3_open (char * szDbFileName, sqlite3 ** db)
Sqlite3_exec (sqlite3 * db, char * szSqlCMD, callback, 0, char ** zErrMsg)
Sqlite3_close (sqlite3 * db)
Static int callback (void * NotUsed, int argc, char ** argv, char ** azColName)
2.sqlite3_exec (), execute the SQL command:
int sqlite3_exec (
    sqlite3 * db, / * An open database * /
    const char * sql, / * SQL to be executed * /
    sqlite_callback, / * Callback function callback function name * /
    void * data / * 1st argument to callback function * /
    char ** errmsg / * Error msg written here * /
);
Sqlite3_exec () contains a callback mechanism that provides a way to get results from a SELECT statement.

The third parameter of the sqlite3_exec () function is a pointer to a callback function. If a callback function is provided, SQLite will call the callback function for each record encountered when the SELECT statement is executed, that is, sqlite3_exec () executes An SQL statement executes the sqlite_callback function once every result is returned, which is convenient for us to process the query data.

3.callback () is a callback function that is passed to sqlite3_exec's callback function to display the query results. This callback function is called once for each query result:
typedef int (* sqlite3_callback) (
    void * data, / * Data provided in the 4th argument of sqlite3_exec () passed by the 4th parameter of sqlite3_exec () * /
    int ncols, / * The number of columns in row The number of columns returned by the query, that is, the number of header columns * /
    char ** values, / * An array of strings representing fields in the row
    char ** headers / * An array of strings representing column names * /
);
Its parameters:

The fourth parameter (the this pointer) passed in data: sqlite3_exec (), through the data parameter, you can pass some special pointers (such as class pointers, structure pointers), and then cast them to the corresponding type (here is void * Type must be cast to that type to be available). Both sqlite3_exec () and callback () have this formal parameter. This parameter is of great use. You can pass a pointer to an object to the callback function, and then cast void * to the original type for some operations, such as pushing the stack.
Values: a data array pointer of the query record, a pointer array to the query result, which can be obtained by sqlite3_column_text ().
Headers: is a pointer to the column name array of the table header, an array of pointers to the table header name, which can be obtained by sqlite3_column_name ().
Its return value is 0 or 1:

Returns zero: sqlite3_exec () will continue to execute the query.
Returns non-zero: sqlite3_exec () will immediately interrupt the query, and sqlite3_exec () will return SQLITE_ABORT.
Example callback parameters:

Table
ID NAME ADDRESS AGE
1 YSP ShangHai 22
2 HHB ShangHai 25

select * from Table

The first record is queried, and the callback function is called once:
Ncols = 4 (4 fields in total)
Values [0]: "1"; values [1]: "YSP"; values [2]: "ShangHai"; values [3]: "22"
Headers [0]: "ID"; headers [1]: "NAME"; headers [2]: "ADDRESS"; headers [3]: "AGE"

The second record is queried, and the callback function is called a second time:
Ncols = 4 (4 fields in total)
Values [0]: "1"; values [1]: HHB; values [2]: ShangHai; values [3]: 25
Headers [0]: ID; headers [1]: NAME; headers [2]: ADDRESS; headers [3]: AGE
Note: The values queried by sqlite3_exec () are all char * types, and type conversion may be required to meet the requirements.

If the data type of a column is not char *, you can perform related conversions on the result, such as: using atoi () to convert the result to an integer (integer), and if it is binary data, you can directly cast the type, such as: (void *) values [i].

Program example:


#include <stdio.h>  
#include <stdlib.h>  
#include "util.h"  
#pragma comment(lib, "sqlite3.lib")  
  
int callback(void* data, int ncols, char** values, char** headers);  
  
int main(int argc, char **argv)  
{  
    sqlite3 *db;  
    int rc;  
    char *sql;  
    char *zErr;  
    char* data;  
  
    rc = sqlite3_open("test.db", &db);  
    if(rc)   
    {  
        fprintf(stderr, "Can‘t open database: %s\n", sqlite3_errmsg(db));  
        sqlite3_close(db);  
        exit(1);  
    }  
      
    data = "Callback function called";  
    sql = "insert into episodes (name, cid) values (‘Mackinaw Peaches‘, 1);"  
          "select * from episodes;";  
    rc = sqlite3_exec(db, sql, callback, data, &zErr);  
  
    if(rc != SQLITE_OK)   
    {  
        if (zErr != NULL)  
        {  
            fprintf(stderr, "SQL error: %s\n", zErr);  
            sqlite3_free(zErr);  
        }  
    }  
  
    sqlite3_close(db);  
  
    return 0;      
}  
  
int callback(void* data, int ncols, char** values, char** headers)  
{  
    int i;  
    fprintf(stdout, "%s: ", (const char*)data);  
    for(i=0; i < ncols; i++)   
    {  
        fprintf(stdout, "%s=%s ", headers[i], values[i]);  
    }  
  
    fprintf(stdout, "\n");  
    return 0;  
}  


Description: Call the callback () function on each record queried in the execution result of sqlite3_exec ().

相应 The corresponding field value of each record is stored in the values array, and the table header is stored in the headers array, which can complete the corresponding data processing.

SQLite source program analysis callback mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.