sqlite3也是一种文件, 是文件无外乎打开,读,写(更新),关闭.
读
sqlite3 *db = NULL;
int result = sqlite3_open("/tmp/testDb.db", &db);
if(result!=SQLITE_OK)
{
//打开失败
}读写(sql语句实现)
char *cError = NULL; // 用来存储错误信息
char *cSql = "create table if not exists testDb1(id integer primary key auto_increment, name text, age integer);";
int iResult = sqlite3_exec(db, cSql, NULL, NULL, &cError);
if (iResult != SQLITE_OK)
{
sqlite3_close(db);
//执行错误
sqlite3_free(cError);
}
sqlite3_exec的结构如下
int sqlite3_exec(
sqlite3* ppDb, /* An open database */
const char *sql, /* SQL to be evaluated */
int (*callback)(void*,int,char**,char**), /* Callback function */
void *, /* 1st argument to callback */
char **errmsg /* Error msg written here */
);第1个参数是前面open函数得到的指针。
第2个参数const char *sql是一条sql 语句,以\0结尾。
第3个参数sqlite3_callback 是回调,当这条语句执行之后,sqlite3会去调用你提供的这个函数。
第4个参数void*是个参数, 最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL。
第5个参数char** errmsg 是错误信息。通常,sqlite3_callback 和它后面的void*这两个位置都可以填NULL。填NULL表示你不需要回调。
关于回掉函数使用示例如下:
char *cSql = "select * from fuck";
char *cErr;
int iResult = sqlite3_exec(db,cSql,callback,NULL,&cErr);
if (iResult != SQLITE_OK)
{
sqlite3_close(db);
//执行错误
sqlite3_free(cError);
}int callback(void * ,int iCount,char** ppValue,char** ppName)
{
string s; //c++
for(int i=0;i< iCount;i++)
{
s+=pName[i];
s+=":”;
s+=pValue[i];
s+="\n”;
}
cout<< s<< endl;
return 0;
}关闭
sqlite3_close(db);
//执行错误
sqlite3_free(cError);