常見sqlite3 API的簡單使用(2)
阿新 • • 發佈:2020-11-06
sqlite3_get_table
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 */ ); void sqlite3_free_table(char **result);
官網不推薦使用這個API,官網不推薦使用這個API,官網不推薦使用這個API。
使用該API可以得到一個結果表。結果表包含全部的查詢結果,是一個含有指標的陣列。
陣列地址由azResult得到, 我們傳入的是&azResult 。
每個指標指向一個查詢資料(字串形式)。
例子(官網):
查詢到的結果如下。
Name | Age ----------------------- Alice | 43 Bob | 28 Cindy | 21
azResult 如下。
azResult[0] = "Name"; azResult[1] = "Age"; azResult[2] = "Alice"; azResult[3] = "43"; azResult[4] = "Bob"; azResult[5] = "28"; azResult[6] = "Cindy"; azResult[7] = "21";
查詢結果的行數由nRow得到,我們傳入的是&nRow 。(nRow = 3)
查詢結果的列數由nColumn得到,------------------------。(nColumn = 2)
注意注意注意
用完之後需要使用 sqlite3_free_table 釋放 azResult 上 的記憶體。
用完之後需要使用 sqlite3_free_table 釋放 azResult 上 的記憶體。
用完之後需要使用 sqlite3_free_table 釋放 azResult 上 的記憶體。
返回
成功執行返回 SQLITE_OK
測試例項
#include <iostream> #include <stdio.h> #include "sqlite3.h" using namespace std; int main() { sqlite3 * db; char **azResult; int nRow, nColumn; int rv = sqlite3_open("./test.db", &db); if(rv != SQLITE_OK){ fprintf(stderr, "db can't open\n"); return -1; } rv = sqlite3_get_table(db, "select * from user", &azResult, &nRow, &nColumn, nullptr); if(rv != SQLITE_OK) { fprintf(stderr, "func failed\n"); return -2; } int left = 0; for(int i = 0; i < nRow + 1; i++){ for(int j = 0; j < nColumn; j++){ printf("%s\t\t\t", azResult[left++]); } cout << endl; } sqlite3_free_table(azResult); sqlite3_close(db); return 0; }
Name | Age ----------------------- Alice | 43 Bob | 28 Cindy | 21