sqlite3的C接口

sqlite3也是一种文件, 是文件无外乎打开,读,写(更新),关闭.


  1. sqlite3 *db = NULL;
    int result = sqlite3_open("/tmp/testDb.db", &db);
    if(result!=SQLITE_OK)
    {
    //打开失败
    }

  2. 读写(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;
    }

  3. 关闭
    sqlite3_close(db);
    //执行错误
    sqlite3_free(cError);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值