2

我正在尝试插入一些数据 sqlite 数据库...我确信插入查询是正确的,因为我从终端和 sqlite 管理器测试了它,但它不是从 ios5 插入的...请帮助!!!

-(BOOL)insertWithRawQuery:(NSString*) query
{
        sqlite3_stmt    *statement;
        BOOL success = NO;
        if (sqlite3_open([databaseFilePath UTF8String], &database) == SQLITE_OK)
        {
            NSLog(@"%@",query);
            const char *insert_stmt = [query UTF8String];

            sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
            if (sqlite3_step(statement) == SQLITE_DONE)
            {
                success=YES;
            } else 
            {
                success=NO;
                NSLog(@"%d",sqlite3_step(statement));
            }
            sqlite3_finalize(statement);
       }
         sqlite3_close(database);
        return success;
}

    NSLog(@"%d",sqlite3_step(statement))

打印 21 这是 SQLITE_MISUSE ..你知道吗?

4

2 回答 2

7

这就是我在 iOS 5 中将数据插入 sqlite 的方式,它工作正常。

-(void) checkAndCreateDatabase{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:databasePath];
    if(success) return;
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}

-(void) openDatabase
{   
    NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentsPaths objectAtIndex:0];   
    databasePath = [documentDir stringByAppendingPathComponent:YOUR_DATABASE_NAME];
    [self checkAndCreateDatabase];  
    if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_OK)
        NSLog(@"Database opened.");
}

-(BOOL)insertDataWithUsername:(NSString*)name withPassword:(NSString*)password withAge:(int)age
{
    [self openDatabase];
    NSString *query = nil;
    query = [NSString stringWithFormat:@"INSERT INTO your_table(name, password, age) Values('%@','%@', %d)", name, password, age];

    sqlite3_stmt *compiledStatement;
    if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) 
    {   
        if(SQLITE_DONE != sqlite3_step(compiledStatement))
            NSLog( @"Error while inserting data: '%s'", sqlite3_errmsg(database));
        else NSLog(@"New data inserted");

        sqlite3_reset(compiledStatement);       
    }else
    {
        NSLog( @"Error while inserting '%s'", sqlite3_errmsg(database));
    }
    sqlite3_finalize(compiledStatement);
}
于 2012-06-29T17:06:31.377 回答
0

我认为作为参数发送的查询是问题的根源。查询构造可能使用了一些自动释放的变量或其他东西。请使用 XCode->Product Tab-> profile-> 选择 NSZombie-> 并运行程序检查是否有任何用于构造查询的对象被自动释放。

于 2012-06-29T19:40:00.287 回答