Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to save and fetch data from Sqlite database

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 291
    Comment on it

    First include the sqlite file in your project. Then copy that file from bundle to documents directory as below and create Database method.

    -(void)createDatabase{
        NSString *pathForDocumentDirectory =[self databasePath]; //define new path and put old path in new one
        
        if ([[NSFileManager defaultManager]fileExistsAtPath:pathForDocumentDirectory]) {
            return;
            
        }
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"myDatabase" ofType:@"sqlite"];
        NSLog(@"bundle path %@",path);
        
        NSLog(@"doc dir path %@",pathForDocumentDirectory);
        NSError *error;
        [[NSFileManager defaultManager] copyItemAtPath:path toPath:pathForDocumentDirectory error:&error];
        
        if (error) {
            NSLog(@"error while transferring file=> %@",error.localizedDescription);
        } else {
            NSLog(@"db file saved in documents");
        }
        
    }

     

    For Database path we can use below method.

    -(NSString *)databasePath{
    
    
        //define the property of databasepath ,path start from zero.
    
    
        NSString *pathForDocumentDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex:0];
        
        pathForDocumentDirectory=[pathForDocumentDirectory stringByAppendingPathComponent:@"myDatabase.sqlite"];  //add myDatabase in this, myDatabase is the database which we created
        
        return pathForDocumentDirectory; //got database path in pathForDocumentDirectory
        
    }

    By using below code we can save data in database.

    -(BOOL)saveRecordsInDb {
        
        const char *databasePath = [self.databasePath UTF8String];  //convert db path in char formate
        
        if (sqlite3_open(databasePath, &database) == SQLITE_OK)  //open database
        {
            
            NSString *insertData = [NSString stringWithFormat:@"insert into myTable (firstName,lastName) values (\"%@\",\"%@\")",@"jaya",@"arti"]; //myTable is the table name having two columns first name and last name.
            
            const char *insert_stmt = [insertData UTF8String]; // converting insertData into char
            
            sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);//prepare statement
            
            BOOL success;
            
            if (sqlite3_step(statement) == SQLITE_DONE)//step is used for execution
            {
                success = YES;
            }
            else {
                success = NO;
            }
            
            sqlite3_reset(statement); //reset to value 0
            
            return success;
        }
        return NO;
    }
    
    

    If we want to fetch records then we can use following code. In below code we are printing fetched data.
     

    -(NSArray *)getAllDetailsFromDb{
        
        const char *databasePath = [self.databasePath UTF8String]; //converting databasePath path into char
        
        NSMutableArray *resultArray = [NSMutableArray new];
        
        if (sqlite3_open(databasePath, &database) == SQLITE_OK)
        {
            
            NSString *getDetails = [NSString stringWithFormat:@"select * from myTable];
            
            const char * get_stmt = [getDetails UTF8String];//convert getDetails into char formate
            
            if (sqlite3_prepare_v2(database,
                                   get_stmt, -1, &statement, NULL) == SQLITE_OK)//for connection
            {
                
                while (sqlite3_step(statement) == SQLITE_ROW)
                {
       //it will run values column by column so we have to write column 0 ,column1 and all.
    
                   NSString *firstDetail = [[NSString alloc] initWithUTF8String:
                                       (const char *) sqlite3_column_text(statement, 0)];
                    NSString *secondDetail = [[NSString alloc] initWithUTF8String:
                                       (const char *) sqlite3_column_text(statement, 1)];
                    
    
                    NSLog(@"checks are %@ %@ ",firstDetail,secondDetail);
                               
                }
                
                sqlite3_reset(statement);
            }
            
            else{
                NSLog(@"Not found");
                return nil;
            }
        }
        NSLog(@"%@",resultArray);
        return resultArray;
    }
    
    
    
    
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: