1

我正在使用下面的代码来创建 sqlite DB,但是我无法通过执行查询插入值,谁能告诉我我哪里错了?

 - (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) return;

    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DATABASE_NAME];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

初始化数据库

    - (void)initializeDatabase {    

    // The database is stored in the application bundle. 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
        // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) 
    {      
        //TRUE
    } 
    else 
    {
        // Even though the open failed, call close to properly clean up resources.
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
        // Additional error handling, as appropriate...
    }

}

执行 Sql 方法

        -(void)ExecuteSQL:(NSString*)SQL
    {

            @synchronized(self)
        {

            sqlite3_stmt *select_statement=nil;

            if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &select_statement, NULL) != SQLITE_OK) {
                NSString *errString = [NSString stringWithFormat:@"%@", 
                          [NSLocalizedString(@"statementPrepareFailedKey",@"")          
                          stringByReplacingOccurrencesOfString:@"#" withString:[NSString 
                          stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding] ]];
                NSAssert1(0, @"%@", errString);
            }

            //int columncount=sqlite3_column_count(select_statement);

            //NSMutableDictionary* dic;

            if(sqlite3_step(select_statement) == SQLITE_DONE) 
            {   
                NSLog(@"Execute sql");
            }

            sqlite3_finalize(select_statement);
        }

    }

谢谢。

4

0 回答 0