gpt4 book ai didi

c - 如何在 sqlite3 中将 json 数组索引设置为绑定(bind)参数?

转载 作者:太空宇宙 更新时间:2023-11-04 04:24:49 26 4
gpt4 key购买 nike

我正在为 SQLite3json1 扩展使用 C-API。在数据库中,整数列表存储为 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]',作为一个边界参数,如下面的代码片段所示。

我可以或应该避免使用 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);
}

最佳答案

您可以在 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);
}

关于c - 如何在 sqlite3 中将 json 数组索引设置为绑定(bind)参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42742365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com