Sqlite3多值查询结果信息读取

缘由

最近在学嵌入式开发,最后要求做一个带GUI的操作界面,我负责的是用户信息查询和另一个道具提示的界面(如下图,某用户的ssr>10则给与的提示信息)。界面什么的都还好说,自己难在了数据查询后如何获取具体值这里了。自己上课了解的都只是判断数据有无,但对于具体的操作,甚至是多值返回结果给卡住了!因为返回值类型是char ** 类型,我还搞到了二维指针去了。可能由于始终在脑海里对于数据库总是表的结构,然后走了不少歪路。后来弄了许久才明白就是一维数组的存储结构;

详解

直接上图,只管易懂;我这里创建了一个user表,有id、name、password表头;图中的表格是我化的表格,而获取的值则以数组形式返回;

代码

/*
 * author:emperinter
 * 
 * website:https://www.emperinter.info/
 *
 */
#include<sqlite3.h>
#include<stdio.h>

sqlite3 * db;

int main(){
    sqlite3_open("database.db",&db);

    int rc,nRow,nColum,i;
    char ** dbresult = NULL;   //get the sql result
    char *zErrMsg = NULL;

    //create table user
    sqlite3_exec(db,"create table user (id int,name text, password text);",NULL,NULL,&zErrMsg);

    //insert some data to database
    sqlite3_exec(db,"insert into user (id,name,password) values(0,'lover','521');",NULL,NULL,&zErrMsg);
    sqlite3_exec(db,"insert into user (id,name,password) values(1,'cute','emperinter');",NULL,NULL,&zErrMsg);

    rc = sqlite3_get_table(db, "select id,name,password from user where id < 3;", &dbresult, &nRow, &nColum, &zErrMsg);
    printf("%d\n",nColum);
    printf("%d\n",nRow);
    printf("****************\n");
    if(rc == SQLITE_OK) {
        for( i=0 ; i<( nRow + 1 ) * nColum ; i++ )  
            printf( "Result[%d] = %s\n", i , dbresult[i] );  
    }else
    {
        printf("No Data!\n");
    }

    printf("*****************\n");
    printf("printf OK!\n");
    sqlite3_free_table(dbresult);
    sqlite3_close(db);

    return 0;
}
  • 运行结果如图所示

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *