前面说到的 sqlite_exec() 中的第三个参数, SQLite 将为 sql 参数内执行的每个 SELECT 语句中处理的每个记录调用这个回调函数。
本节添加了两个函数,selectFromTable和updateTable.
实例程序如下:
#include#include #include "sqlite/sqlite3.h" #define DB_NANE "sqlite/test.db" sqlite3 *db = NULL; char* sql = NULL; char *zErrMsg = NULL; const char* data = "Callback function called";/* 改为全局的 */ int ret = 0; typedef enum{ false, true } bool; /* typedef int (*sqlite3_callback)( void*, Data provided in the 4th argument of sqlite3_exec() int, The number of columns in row char**, An array of strings representing fields in the row char** An array of strings representing column names ); */ static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i = 0; for(i=0; i bool selectFromTable()/*新加*/ { /* Create SQL statement */ sql = "SELECT * from COMPANY"; /* Execute SQL statement */ ret = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( ret != SQLITE_OK ){ fprintf(stderr, "Error SQL: %s\n", zErrMsg); sqlite3_free(zErrMsg); return false; } fprintf(stdout, "successfully operation done\n"); return true; }bool updateTable()/* 新加 */ {     /* Create merged SQL statement */     sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \     "SELECT * from COMPANY";          /* Execute SQL statement */     ret = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);     if( ret != SQLITE_OK ){         fprintf(stderr, "SQL error: %s\n", zErrMsg);         sqlite3_free(zErrMsg);                  return false;     }          fprintf(stdout, "Successfully operation done \n");          return true; }
bool closeDB() { int ret = 0; ret = sqlite3_close(db); if ( ret == SQLITE_BUSY ){ return false; } return true; } int main(int argc, char* argv[]) { connectDB(); /*createTable();*/ /*insertRecords();*/ selectFromTable(); updateTable(); selectFromTable(); closeDB(); return 0; }