如何在Sqlite中插入记录?

时间:2010-11-30 05:39:37

标签: iphone objective-c sqlite ios4

请有人告诉我如何通过目标c在sqlite中插入记录吗?

2 个答案:

答案 0 :(得分:3)

您可以使用像这样的代码块

-(NSString*) GetDatabasePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
        NSUserDomainMask, YES) ;
    NSString *documentsDirectory = [paths objectAtIndex:0] ;
    return [documentsDirectory stringByAppendingPathComponent:@"Your Database"] ;
}

-(void)InsertPurchase {
        sqlite3_stmt *statement=nil;
        NSString *path = [self GetDatabasePath];
        NSString *query;

        if(sqlite3_open([path UTF8String],&db) == SQLITE_OK)
        {
            query = [NSString stringWithFormat: @"Your insert query"];

            if(sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, NULL)
                        == SQLITE_OK)
            {
                sqlite3_step(statement);
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(db);
}

这可以是您的界面

@interface Database : NSObject {
    sqlite3 *db;
}

答案 1 :(得分:1)

如果你正在使用FMDB(老实说如果你不是你疯了),那真的很简单:

FMDatabase* db = [FMDatabase databaseWithPath:@"/path/to/my/database.db"];
if ([db open]) {
  [db executeUpdate:@"insert into myTable (col1, col2) values (?, ?)", @"foo", [NSNumber numberWithInt:42]];
  [db close];
}