当先锋百科网

首页 1 2 3 4 5 6 7

前面说到的 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;

static int callback(void *NotUsed, int argc, char **argv, char **azColName)

{

int i = 0;

for(i=0; i < argc; i++){

printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");

}

printf("\n");

return 0;

}

bool connectDB()

{

ret = sqlite3_open(DB_NANE, &db);

if( ret != SQLITE_OK){

fprintf(stderr, "Error open database: %s\n", sqlite3_errmsg(db));

sqlite3_free(zErrMsg);

return false;

}

fprintf(stdout, "Successfully opened database\n");

return true;

}

bool createTable()

{

sql = "CREATE TABLE COMPANY(" "ID INT PRIMARY KEY NOT NULL," "NAME TEXT NOT NULL," "AGE INT NOT NULL," "ADDRESS CHAR(50)," "SALARY REAL );";

ret = sqlite3_exec(db, sql, callback, 0, &zErrMsg);

if( ret != SQLITE_OK ){

fprintf(stderr, "Error SQL: %s\n", zErrMsg);

sqlite3_free(zErrMsg);

return false;

}

fprintf(stdout, "Successfully table created\n");

return true;

}

bool insertRecords()

{

sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";

ret = sqlite3_exec(db, sql, callback, 0, &zErrMsg);

if( ret != SQLITE_OK ){

fprintf(stderr, "SQL error: %s\n", zErrMsg);

sqlite3_free(zErrMsg);

return false;

}

fprintf(stdout, "successfully records created\n");

return true;

}bool selectFromTable()

{

sql = "SELECT * from COMPANY";

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()

{

sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; "     "SELECT * from COMPANY";

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();

selectFromTable();

updateTable();

selectFromTable();

closeDB();

return 0;

}

原文:http://blog.csdn.net/xufeng0991/article/details/38598313