【问题标题】:How to set json array index as bound parameter in sqlite3?如何将 json 数组索引设置为 sqlite3 中的绑定参数?
【发布时间】:2017-08-02 05:07:49
【问题描述】:

我将 C-API 用于 SQLite3json1 扩展。在数据库中,整数列表存储为 json_array。我想使用 json_extract 函数从 json_array 创建一个 C 整数数组。我通过增加 SQL 语句中的索引来循环遍历 json 数组中的每个值。例如,考虑:

CREATE TABLE mytable ( label INTEGER PRIMARY KEY, list TEXT);
INSERT INTO mytable VALUES ( 1, json(json_array(1,2,3)) ); 

SELECT json_extract( list, '$[index]' ) FROM mytable WHERE label == 1;
---Example: the result for index=0 is the integer: 1

在C程序中,我目前正在创建一个字符串来表示命令的单引号部分,'$[index]',作为绑定参数,如下面的sn-p所示.

我可以或应该避免使用sprintf 来设置索引吗?或者,这是一个可以接受的解决方案吗?

char *sql = "select json_extract(list, ?) from mytable where label == 1";
char *index_param = (char *)malloc(80);

// OTHER STUFF: prepare sql stmt, etc, etc...

for (int i=0; i<n; i++) {  /* n is the number of values in the json list */

    /* Is sprintf the best thing to do here? */
    index_length = sprintf(index_param, "$[%d]", i);

    sqlite3_bind_text(stmt, 1, index_param, index_length+1, SQLITE_STATIC);
    result = sqlite3_step(stmt);
    values[i] = sqlite3_column_int(stmt, 0);
    sqlite3_reset(stmt);
}

【问题讨论】:

    标签: c json sqlite sqlite-json1


    【解决方案1】:

    你可以在 SQL 中构造路径,这样你就只有一个整数参数:

    SELECT json_extract(list, '$[' || ? || ']') FROM ...
    

    但最好直接使用json_each() 函数读取数组值:

    const char *sql = "SELECT value FROM MyTable, json_each(MyTable.list) WHERE ...";
    // prepare ...
    for (;;) {
        rc = sqlite3_step(stmt);
        if (rc != SQLITE_ROW)
            break;
        values[i++] = sqlite3_column_int(stmt, 0);
    }
    

    【讨论】:

    • json_each() fcn 非常有用,您的回答让我找到了解决方案!但是,为了获得正确的行为,我使用了 if (rc == SQLITE_DONE) break; 而不是 !=
    • 抱歉,应该是 ROW。使用 DONE,它永远不会在出错后结束。
    猜你喜欢
    • 2017-10-26
    • 2015-06-06
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2019-06-02
    相关资源
    最近更新 更多