【问题标题】:sqlite3_prepare_v2 problemsqlite3_prepare_v2 问题
【发布时间】:2011-03-18 08:42:22
【问题描述】:

我收到以下错误:

* 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'* +[NSString stringWithUTF8String:]: NULL cString'

在下面的代码行:

NSString *aName = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];

我不确定这里发生了什么,我在 SQL 语句中引用的列包含数据。完整代码如下。

// Open the database from the users filessytem
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
    {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = "select ZROUTE_NAME from ZROUTE";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
        {
            // Loop through the results and add them to the Route Name array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) 
            {
                // Read the data from the result row
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

                // Add the animal object to the animals Array
                //[list addObject:animal];              
                [list addObject:aName];             
                //[animal release];
            }
        }
        else 
        {
            NSLog(@"Error: failed to select details from database with message '%s'.", sqlite3_errmsg(database));
        }

        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);        
    }
    sqlite3_close(database);

【问题讨论】:

    标签: iphone objective-c xcode sqlite


    【解决方案1】:

    啊 :p - 我相信 - 如果你执行以下语句,你就不会遇到麻烦。

    这永远不会抛出你提到的异常 - * 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'* +[NSString stringWithUTF8String:]: NULL cString'

    但请记住 - 当有 空值 - 你的字符串将有 (null)

    NSString *bName=[NSString stringWithFormat: @"%s",(char *)sqlite3_column_text(compiledStmt, 0)];
    

    就是这样。如果觉得有帮助,请点赞。 :)

    【讨论】:

    • 我喜欢这个,但它提出了一个问题,如果我的数据库中有NULL,我是否想要nil NSString *...。嗯
    【解决方案2】:

    处理语句的空指针条件

    if((char*)sqlite3_column_text(compiledStatement, 1) != NULL)
    {
          NSString *aName = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];
    }
    

    这将解决您的问题。

    谢谢,
    吉姆。

    【讨论】:

    • 这有完全相同的问题。您不应该检查 NSString,而是检查原始 C 字符串。
    • 是的,我的错。现已更正。谢谢 JoostK。
    • 感谢 Jim 和 JoostK,我已按上述方式更改了代码。请注意,我不得不将 sqlite3_column_text(compiledStatement, 1) 更改为 sqlite3_column_text(compiledStatement, 0),不太清楚为什么,但它现在可以工作了。
    • 这里一样,如果可以将结果存储在变量中,为什么要调用两次函数? @ste
    • 为什么 if ((char*)sqlite3_column_text(compiledStatement, 1)) 条件不起作用?为什么我们必须检查 not null?
    猜你喜欢
    • 2015-02-07
    • 2011-07-05
    • 2014-04-15
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多