加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

sqlite3 读取表数据

发布时间:2020-12-12 19:57:39 所属栏目:百科 来源:网络整理
导读:先上一段 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: %sn",
先上一段 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: %sn",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 = %dn",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); 释放掉占用的内存

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读