簡體   English   中英

有沒有辦法系統地查詢sqlite3行以將數據放入C數組中?

[英]Is there a way to systematically query sqlite3 rows to put the data into a C array?

我正在編寫一個輕巧,快速的Gtk應用程序,它的大小應足夠小,以供空白的獨立Rasberry Pi安裝程序使用,以便我的工作同事進行自我排練。 輸出將是拇指驅動器上的CSV文件,供我的Line Manager在Excel中打開。 對我來說,讀寫.xlsx文件可能是一個太遙遠的步驟……^ _〜

Sqlite數據庫用於永久存儲。

我需要知道是否有一個功能,使我能夠系統地查詢行以將數據復制到數組(也許也為結構)中,以進行C語言分析(名冊沖突等)。 我讀過Java有Cursors,C等效項是什么?

我需要知道是否存在使我能夠系統地查詢行以將數據復制到數組(也許也是結構)中以便在C中進行分析的功能

在SQLite的C API中,沒有將整個數組或結構與SQLite行關聯的功能。 您將需要使用sqlite3_column_xxx()檢索結構或數組中的每個元素(例如, sqlite3_column_int()以檢索整數值)。

例如,假設您具有以下struct

typedef struct {
    int employee_id;
    int day_of_month;
    int shift_no;
} roster_entry_t;

以及具有匹配模式的SQLite表,您將使用以下函數檢索這些結構的數組:

int get_roster_entries(sqlite3 *db, roster_entry_t *roster, int max,
                       int *count) {
    sqlite3_stmt *stmt = NULL;
    int rc = 0;
    int i = 0;

    rc = sqlite3_prepare_v2(
        db, "SELECT employee_id, day_of_month, shift_no FROM roster LIMIT ?",
        -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Failed to prepare SQL: %s\n", sqlite3_errmsg(db));
        return 1; 
    }
    rc = sqlite3_bind_int(stmt, 1, max);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Problem setting limit: %s\n", sqlite3_errmsg(db));
        return 1;
    }

    do {
        roster_entry_t *entry = &roster[i++];
        rc = sqlite3_step(stmt);
        if (rc == SQLITE_DONE) {
            printf("No more rows ...\n");
            break;
        } else if (rc != SQLITE_ROW) {
            fprintf(stderr, "Problem: %s\n", sqlite3_errmsg(db)); 
            sqlite3_finalize(stmt);
            return 1;
        }
        entry->employee_id = sqlite3_column_int(stmt, 0);
        entry->day_of_month = sqlite3_column_int(stmt, 1);
        entry->shift_no = sqlite3_column_int(stmt, 2);
    } while (i < max);
    *count = i - 1;

    sqlite3_finalize(stmt);
    return 0; 
}

筆記

  • 可以使用sqlite3_bind_xxx()將程序中的變量與SQL中的占位符關聯。
  • 盡管它使代碼更加冗長,但確實值得檢查SQLite函數的返回值。
  • 對於數組索引sqlite3_bind_xxx()從1開始,而那些用於sqlite3_column_xxx()開始0(有點混亂)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM