Search code examples
iphoneobjective-csqliteios4

How to insert a record in Sqlite?


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


Solution

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