sqlite3 读取表数据

来源:互联网 发布:卖家怎么联系淘宝达人 编辑:程序博客网 时间:2024/05/16 08:01
先上一段 sample
 
#include <stdio.h>#include <string.h>#include "sqlite3.h"int main(){sqlite3 *db;char *zErrMsg = 0;int rc;char **result;int row, column;int i, j;rc = sqlite3_open("gt_db.db", &db);if( rc ){fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));sqlite3_close(db);return -1;}rc = sqlite3_get_table(db, "SELECT * FROM DeviceMap", &result, &row, &column, &zErrMsg);if (rc == SQLITE_OK) {printf("row = %d, column = %d\n", row, column);printf(result[0]);for (i = 0; i <= row; i++) {printf("----------- %d -------------\n", i);for (j = 0; j < column; j++) {printf("%s  ",  result[i*column + j]);}}}sqlite3_free_table(result);sqlite3_close(db);return 0;}


其实,读取表数据只要用 sqlite3_get_table 就可以了,当然,也可以用 sqlite3_exec 然后在回调里查。

官方的说明,讲了一大堆,还举了实例,就怕你看不懂,结果还真是越讲越糊涂了。

SQLITE_API int sqlite3_get_table(  sqlite3 *db,          /* An open database */  const char *zSql,     /* SQL to be evaluated */  char ***pazResult,    /* Results of the query */  int *pnRow,           /* Number of result rows written here */  int *pnColumn,        /* Number of result columns written here */  char **pzErrmsg       /* Error msg written here */);


其实是要注意结构就明白了,举个例子

      Name        | Age
        -----------------------
      Alice          | 43
       Bob          | 28
       Cindy       | 21


这个数据表里,有两个字段 Name    和 Age,   那在一段内存里怎么表示呢?

其实就是用二维数组。

pnRow ---   表示有几条记录;

pnColumn -- 表示有几个内容,即有几个字段;

 

那在上面这个示例中

 pnRow = 3,    pnColumn = 2

 

如果我要取 Bob 这个人的记录,则

(*pazResult)[pnColumn * 2 + 0]   取出名字  bob

(*pazResult)[pnColumn * 2 + 1]   取出年龄

 

这样会不会比 sqlite3_exec 方便呢?

当然,查完之后,要用 sqlite3_free_table(result);  释放掉占用的内存

 

 

0 0