int sqlite3_open( const char *filename,/* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: sqlite db handle */ );
filename参数是文件名,或字符串':memory:',或一个空指针(NULL)。用后两者将创建内存数据库。
int sqlite3_close(sqlite3*);
int sqlite3_exec( sqlite3*,/* An open database */ const char *sql,/* sql to be executed */ sqlite_callback,/* Callback function */ void *data /* 1st argument to callback function */ char **errmsg /* Error msg written here */ );
sqlite3_exec()包含一个回叫(callback)机制,提供了一种从SELECT语句得到结果的方法
sqlite3_exec()函数第3个参数是一个指向回叫函数的指针,如果提供了回叫函数,sqlite则会在执行SELECT语句时为遇到的每一条记录都调用回叫函数
回叫函数:callback()
typedef int (*sqlite3_callback)( void* data,/* Data provided in the 4th argument of sqlite3_exec() */ int ncols,/* The number of columns in row */ char** values,/* An array of strings representing fields in the row */ char** headers /* An array of strings representing column names */ );
示例:
#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,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; }原文链接:https://www.f2er.com/sqlite/202135.html