gpt4 book ai didi

iphone - 如何将文字文本绑定(bind)到 SQLite 查询?

转载 作者:IT王子 更新时间:2023-10-29 06:31:01 27 4
gpt4 key购买 nike

我正在尝试在我的 iPhone 应用程序中使用 SQLite C API。我正在尝试查询 SQLite 数据库以获取在特定日期后完成的记录数。数据库将完成日期保存为文本

YYYY-MM-dd
format. For example the text
2009-04-10
might appear as a completed date.

When I query the database from the commandline my query works, but when run from the app, it doesn't. Here's what I'm doing:

From the commandline, I run this query:

sqlite> SELECT COUNT(*) FROM tasks WHERE completed > '2009-04-09'
...> go
1

如您所见,如我所料找到了一条记录。

在我的应用程序中,我执行了这段代码(显然是用 Objective-C 编写的):

static sqlite3_stmt *count_tasks_statement = nil;
if(count_tasks_statement == nil) {
const char *sql = "SELECT COUNT(*) FROM tasks WHERE completed > '?'";

if (sqlite3_prepare_v2(database, sql, -1, &count_tasks_statement, NULL) != SQLITE_OK) {
NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
}

NSString *today = @"2009-04-09";
sqlite3_bind_text(count_tasks_statement, 1, [today UTF8String], -1, SQLITE_TRANSIENT);

// Get the row count from the query
NSInteger taskCount = 0;
if(sqlite3_step(count_tasks_statement) == SQLITE_ROW) {

// The second parameter indicates the column index into the result set.
taskCount = sqlite3_column_int(count_tasks_statement, 0);
}

// Reset the statement for future reuse.
sqlite3_reset(count_tasks_statement);

当我在此代码上使用调试器并检查 taskCount 变量时,它被设置为 0,表示未找到任何记录。 (如果我更改代码以返回找到的行的主键,它仍然不会返回任何内容。)

由于它在命令行中运行,但在我的代码中不起作用,我假设我在我的 SQL 中对问号的引用或将文字文本日期绑定(bind)到询问。但是,我已经尝试了很多不同的方法但没有运气。帮助!

最佳答案

不要将参数占位符放在引号内,即使值是字符串或日期文字也是如此。

const char *sql = "SELECT COUNT(*) FROM tasks WHERE completed > ?";

关于iphone - 如何将文字文本绑定(bind)到 SQLite 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/738279/

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