Home Answers Viewqa Mobile-Applications how to do CRUDE operation in iphone?-RV

 
 


Ravi Vora
how to do CRUDE operation in iphone?-RV
1 Answer(s)      a year and 4 months ago
Posted in : MobileApplications

.h file

#import <sqlite3.h>

@interface RootViewController : UIViewController {

    IBOutlet UIView *page1;
    IBOutlet UIButton *b2;
        IBOutlet UITextField *textid;
    IBOutlet UITextField *textname;

    IBOutlet UILabel *status;
    NSString *databasePath;
    NSMutableArray *temparray;
    //NSMutableDictionary *item;
    //IBOutlet UIButton *btnNextview;

    NSString *databaseName;
    BOOL isInSwipeDeleteMode;

}

@property (assign) BOOL isInSwipeDeleteMode;

-(void)checkAndCreateDatabase;
-(void)getdata;
-(IBAction)savedata;
-(BOOL)UpdateData;
-(IBAction)find:(id)sender;
-(IBAction)keyhide:(id)sender;
-(IBAction)btnTapped:(id)sender;
- (BOOL) validateEmail: (NSString *) candidate;
-(void)delData:(NSString *)path;

@end

.m file

-(void) checkAndCreateDatabase {

    BOOL success;   
    databaseName = @"namedatabase.rdb";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

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

-(IBAction)save_DB
{
    [self checkAndCreateDatabase];
    //[self RemoveData];
    sqlite3 *database;
    static sqlite3_stmt * addStmt ;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    databaseName = @"Photos_db.rdb";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    BOOL success = [fileManager fileExistsAtPath:databasePath];
    if(!success)
    {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Photos_db.rdb"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:databasePath error:&error];
        if (!success)
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }   

    if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        const char *sql = "insert into photo_table(photo_name,photo_date) Values(?,?)";
        if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        sqlite3_bind_text(addStmt, 1, [text_photoname.text UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(addStmt, 2, [text_photodate.text UTF8String], -1, SQLITE_TRANSIENT);
        //sqlite3_bind_text(addStmt, 3, [txtplaceDetail.text UTF8String], -1, SQLITE_TRANSIENT);

        if (sqlite3_step(addStmt) == SQLITE_DONE)
        {
            //status.text = @"Contact added";
            //text_photoname.text = @"";
            //text_photodate.text= @"";
            //photo_img.hidden=YES;
        }
        //phone.text = @"";
        //if(SQLITE_DONE != sqlite3_step(addStmt))

        //    NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
        else
            sqlite3_reset(addStmt);

    }
    else
    {

    }


    sqlite3_close(database);
    [self getdata];
}

-(void)getdata
{
    [self checkAndCreateDatabase];
    sqlite3 *database;

    temparray = [[NSMutableArray alloc] init];

    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {

        NSString *sql = [NSString stringWithFormat:@"select * from newtable"];
        const char *sqlStatement = [sql UTF8String];

         sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                NSMutableDictionary *item=[[NSMutableDictionary alloc] init];
                //NSMutableArray *item=[[NSMutableArray alloc] init];

                [item setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)] forKey:@"eid"];
                [item setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)] forKey:@"ename"];

                [temparray addObject:item];

            }
        }
        sqlite3_finalize(compiledStatement);

    }
    sqlite3_close(database);
    NSLog(@"%@",temparray);
    //NSLog(@"%@",item);
}
-(void)RemoveData
{   
    sqlite3 *database;
    sqlite3_stmt *deleteStmt=nil ;
    [self checkAndCreateDatabase];
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        if(deleteStmt == nil) {
            const char *sql = "delete from newtable where eid = ?";
            if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
                NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
        }

        //When binding parameters, index starts from 1 and not zero.
        const char* the = [delString UTF8String];
        sqlite3_bind_text(deleteStmt, 1, the, -1, SQLITE_TRANSIENT);

        if (SQLITE_DONE != sqlite3_step(deleteStmt))
            NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));

        sqlite3_reset(deleteStmt);
    }
    sqlite3_close(database);


}
-(void)UpdateData
{
    [self checkAndCreateDatabase];
    //sqlite3 *db = [appDelegate database];
    sqlite3_stmt *update_statement;
    sqlite3 *db;


    NSString *sqlStr = [NSString stringWithFormat:@"UPDATE newtable SET ename=\"%@\" WHERE eid=\"%@\" ",txtname.text,txtid.text];
//    NSString *sqlStr = [NSString stringWithFormat:@"UPDATE newtable SET ename=? WHERE eid=?"];
    //const char *sql = "update Coffee Set CoffeeName = ?, Price = ? Where CoffeeID = ?";

//if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)

    const char *sql = [sqlStr UTF8String];
    if(sqlite3_open([databasePath UTF8String],&db)==SQLITE_OK){

    if (sqlite3_prepare_v2(db, sql, -1, &update_statement, NULL) == SQLITE_OK) {
            //UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DatabaseNotAvailable", @"") message:[NSString stringWithUTF8String:sqlite3_errmsg(db)]delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
//            [alert show];   
//            [alert release];
        //return NO;
        //txtid.text=@"";
        //txtname.text=@"";
        statusm.text=@"updated";
    }

    int success = sqlite3_step(update_statement);
    if (success == SQLITE_ERROR) {
        NSAssert1(0, @"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(db));
        //return NO;
    }

    sqlite3_finalize(update_statement);
    }    //return YES;

}

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    //  return 0;
    return [emailTest evaluateWithObject:candidate];
}

-(IBAction)btnTapped:(id)sender{

    if([self validateEmail:textid.text]==1)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Correct Email id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];

        [self savedata];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Incoorect Email id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    }
}
View Answers

January 8, 2012 at 4:04 PM


??









Related Pages:

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.