ошибка при попытке вставить данные в базу данных с помощью sqlite - PullRequest
0 голосов
/ 11 апреля 2011

Библиотечная процедура вне последовательности
Могу ли я узнать, почему возникает эта ошибка (эта ошибка возникает при вставке)

-(void) checkAndCreateDatabase{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:databasePath];

    // If the database already exists then return without doing anything
    if(success) return;

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

    [fileManager release];
}

- (void) readAnimalsFromDatabase { // Настройка объекта базы данных

// Init the animals Array
animals = [[NSMutableArray alloc] init];
// 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 * from sq";
    sqlite3_stmt *compiledStatement;
    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
        // Loop through the results and add them to the feeds array
            NSLog(@"working");
        while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
            // Read the data from the result row
            NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

            // Create a new animal object with the data from the database
            anim *animal = [[anim alloc] initWithName:aName];

            // Add the animal object to the animals Array
            [animals addObject:animal];

            [animal release];
        }
    }
    // Release the compiled statement from memory
    sqlite3_finalize(compiledStatement);

}
sqlite3_close(database);

} // эта функция вызывается из другого файла при нажатии кнопки

-(void)insert:str  
{  
const char *sql = "insert into sq(name) Values ?";  

sqlite3_stmt *compiledStatement;  

if(sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) != SQLITE_OK)  

NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));     
sqlite3_bind_text(compiledStatement, 1, [str UTF8String], -1, SQLITE_TRANSIENT);  

    if(SQLITE_DONE != sqlite3_step(compiledStatement))
        NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
    else
    sqlite3_reset(compiledStatement) ;
}

1 Ответ

2 голосов
/ 11 апреля 2011

Это сообщение об ошибке отображается на SQLITE_MISUSE (исходный код доступен по адресу http://www.sqlite.org).

См. http://www.sqlite.org/faq.html#q6 об ограничениях на использование дескриптора базы данных sqlite3 * из более чем одного потока. По сути, вам разрешено повторно использовать дескриптор базы данных и операторы в разных потоках, но один поток должен полностью завершить доступ к базе данных до запуска другого потока (то есть перекрывающийся доступ не является безопасным). Это похоже на то, что происходит для вас, и согласуется с кодом ошибки SQLITE_MISUSE.

Подробнее Смотрите ниже ТАК сообщение ..

Как правильно вызывать функции SQLite из фонового потока на iPhone?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...