1

我正在为 iPhone 编写一个与 SQLite 数据库通信的应用程序,但我遇到了一个小问题。每当我尝试根据包含撇号的条件查询信息时,都不会返回任何结果......即使存在与请求条件匹配的结果。让我给出一些具体的...

SQLite 表


行--列1--列2----------

  1. 测试数据 - 001
  2. 用户数据 - 002

Objective-C 代码


//Create the sql statement
sqlite3_stmt *sqlStatement;

//Create the name of the category that will be passed in
NSString *categoryName = @"User's Data";

//Create the rest of the SQL query
NSString *sqlQuery = "SELECT * FROM theTableName WHERE Column1 = ?";

//If there are no errors in the SQL query
if (sqlite3_prepare_v2(theDatabase, sqlQuery, -1, &sqlStatement, nil) == SQLITE_OK)
{
    //Bind the category name to the sql statement
    sqlite3_bind_text(sqlStatement, 1, [categoryName UTF8String], -1, SQLITE_TRANSIENT);

    //While there are rows being returned
    while (sqlite3_step(sqlStatement) == SQLITE_ROW)
    {
        //Retrieve row data
    }
}
else
{
    //Save error message to the application log and terminate the app
    NSAssert1(0,@"Error: Failed to prepare the SQL statement with message '%s'.", sqlite3_errmsg(database));
}
//Reset the sql statement
sqlite3_reset(sqlStatement);

我是 Objective C 的半新手,所以在编写这段代码时我的第一个想法是清理用户输入。但是在做了一些研究之后,我读到 sqlite3_bind 调用为你做了必要的清理工作。但是每当代码运行时,while 循环就会被跳过,因为没有返回任何行。它应该从数据库表中返回第二行。如果我将完全相同的SQL 查询复制/粘贴到 SQL 管理程序中(我使用SQLite Manager)(当然还有必要的查询卫生),它会返回正确的数据。

我花了很长时间尝试自己调试它,甚至花费更多时间尝试在线搜索正在解释和解决的类似问题,但无济于事。到目前为止,我只是禁用了用户在 iPhone 的虚拟键盘上键入撇号的功能。但这是我很想在我的成品中包含的一个功能。这里有人可以给我任何有用的提示吗?任何形式的帮助将不胜感激。

4

2 回答 2

7

对于 sqlite,您的请求将是(您可以看到它甚至错误地突出显示):

SELECT * FROM theTableName WHERE Column1 = User's data

它会等待结束的 ' 符号

您应该回显 ' 符号,例如以下列方式:

NSString *sqlQuery = [NSString stringWithFormat:@"SELECT * FROM tableName WHERE Column1=\"%@\"", categoryName];

在这种情况下,查询将是

select * from theTableName where column1="User's data"

这是完全合法的查询。

在这种情况下,您不再需要绑定,最终代码将如下所示:

if (sqlite3_prepare_v2(database, [sqlQuery UTF8String], -1, &sqlStatement, nil) == SQLITE_OK)
{
    //While there are rows being returned
    while (sqlite3_step(sqlStatement) == SQLITE_ROW)
    {
       //Retrieve row data
    }
}
else
{
   //Save error message to the application log and terminate the app
    NSAssert1(0,@"Error: Failed to prepare the SQL statement with message '%s'.", sqlite3_errmsg(database));
}
于 2009-08-26T18:34:46.063 回答
2

正式字符是''

消毒:

NSString *stringToSanitize = @"This is the value with ' character";

NSString *sanitized = [stringToSanitize stringByReplacingOccurrencesOfString:@"'"
                                     withString:@"''"];

然后你可以在你的查询中使用它

于 2010-01-06T01:42:50.203 回答