How to insert a record in Sqlite?

不问归期 提交于 2020-01-24 23:50:13

问题


please anybody tell me how to insert records in sqlite through objective c?


回答1:


You can use a block of code like this

-(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);
}

This can be your interface

@interface Database : NSObject {
    sqlite3 *db;
}



回答2:


If you're using FMDB (and honestly if you don't you're crazy), then it's really simple:

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];
}


来源:https://stackoverflow.com/questions/4310852/how-to-insert-a-record-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!