如何将数据插入到iPhone SDK(xcode)中的sqlite DB中?
谢谢!

最佳答案

首先,您需要使用这两种方法来初始化数据库

-(id) initDatabase{
    databaseName = @"db.sqlite";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    [databasePath retain];

    return self;
}

-(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];
    [fileManager release];
}


然后,您可以与之互动:

if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    static sqlite3_stmt *compiledStatement;
    sqlite3_exec(database, [[NSString stringWithFormat:@"insert into myTable (var1, var2) values ('%@', '%@')", myVar1, myVar2] UTF8String], NULL, NULL, NULL);
    sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);

10-04 23:27