Here is a sample code for connecting with SQLite using Objective-C...
Code:
#import "sqlLiteDemoViewController.h"
@interface sqlLiteDemoViewController () {
    UILabel *lblName;
    UILabel *lblRoll;
    UILabel *lblAge;
    UITextField *txtName;
    UITextField *txtroll;
    UISlider *sldAge;
}
@end
@implementation sqlLiteDemoViewController
- (void)viewDidLoad { 
    NSString *docsDir;
    NSArray *dirPaths;
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    // Build the path to the database file
    _databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"student.db"]];
    NSLog(@"%@",_databasePath);
    NSFileManager *filemgr = [NSFileManager defaultManager];
    if ([filemgr fileExistsAtPath: _databasePath ] == NO)
    {
        const char *dbpath = [_databasePath UTF8String];
        if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt ="CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ROLL TEXT, AGE TEXT)";
           
            if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table");
            }
            sqlite3_close(_contactDB);
            NSLog(@"Connection Successful");
        } else {
            NSLog(@"Failed to open/create database");
        }
    }   
    UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapped)];
    [self.view addGestureRecognizer:tapScroll];
    [super viewDidLoad];
    lblName = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 50)];
    lblName.backgroundColor = [UIColor clearColor];
    lblName.textColor=[UIColor blackColor];
    lblName.text = @"Name";
    [self.view addSubview:lblName];
    lblRoll = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 100, 50)];
    lblRoll.backgroundColor = [UIColor clearColor];
    lblRoll.textColor=[UIColor blackColor];
    lblRoll.text = @"Roll no";
    [self.view addSubview:lblRoll];
    lblAge = [[UILabel alloc] initWithFrame:CGRectMake(10, 130, 100, 50)];
    lblAge.backgroundColor = [UIColor clearColor];
    lblAge.textColor=[UIColor blackColor];
    lblAge.text = @"Age";
    [self.view addSubview:lblAge];
    txtName = [[UITextField alloc] initWithFrame:CGRectMake(80, 40, 200, 40)];
    txtName.borderStyle = UITextBorderStyleRoundedRect;
    txtName.font = [UIFont systemFontOfSize:15];
    txtName.placeholder = @"Specify Name";
    txtName.autocorrectionType = UITextAutocorrectionTypeNo;
    txtName.keyboardType = UIKeyboardTypeDefault;
    txtName.returnKeyType = UIReturnKeyDone;
    txtName.clearButtonMode = UITextFieldViewModeWhileEditing;
    txtName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    txtName.delegate = self;
    [self.view addSubview:txtName];
    txtroll = [[UITextField alloc] initWithFrame:CGRectMake(80, 90, 200, 40)];
    txtroll.borderStyle = UITextBorderStyleRoundedRect;
    txtroll.font = [UIFont systemFontOfSize:15];
    txtroll.placeholder = @"Specify Roll";
    txtroll.autocorrectionType = UITextAutocorrectionTypeNo;
    txtroll.keyboardType = UIKeyboardTypeNumberPad;
    txtroll.returnKeyType = UIReturnKeyDone;
    txtroll.clearButtonMode = UITextFieldViewModeWhileEditing;
    txtroll.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    txtroll.delegate = self;
    [self.view addSubview:txtroll];
    CGRect frame = CGRectMake(80.0, 140.0, 200.0, 40.0);
    sldAge= [[UISlider alloc] initWithFrame:frame];
    [sldAge setBackgroundColor:[UIColor clearColor]];
    sldAge.minimumValue = 0;
    sldAge.maximumValue = 30;
    sldAge.continuous = YES;
    sldAge.value = 15.0;
    [self.view addSubview:sldAge];
    UIButton *subButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    subButton.frame = CGRectMake(80.0, 200.0, 80.0, 30.0);
    [subButton setTitle:@"Store" forState:UIControlStateNormal];
    subButton.backgroundColor = [UIColor clearColor];
    [subButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
    [subButton addTarget:self action:@selector(store:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:subButton];
    UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    srchButton.frame = CGRectMake(200.0, 200.0, 80.0, 30.0);
    [srchButton setTitle:@"Search" forState:UIControlStateNormal];
    srchButton.backgroundColor = [UIColor clearColor];
    [srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
    [srchButton addTarget:self action:@selector(find:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:srchButton];   
}
- (void)tapped {
    [self.view endEditing:YES];
}
-(void)store:(id)sender{
    @try{
    NSLog(@"store called");
        sqlite3_stmt    *statement;
        const char *dbpath = (const char *)[_databasePath UTF8String];
        NSString *age=[NSString stringWithFormat:@"%g", sldAge.value];
        NSLog(@"Age is %@",age);
        if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
        {
            NSString *insertSQL = [NSString stringWithFormat:
                                   @"INSERT INTO STUDENT (name, roll  , age) VALUES (\"%@\", \"%@\", \"%@\")",
                                   txtName.text, txtroll.text, age];
            const char *insert_stmt = [insertSQL UTF8String];
            sqlite3_prepare_v2(_contactDB, insert_stmt, -1, &statement, NULL);
            if (sqlite3_step(statement) == SQLITE_DONE) {
                NSLog(@"Insertion Successful");
            } else {
                NSLog(@"Insertion Failure");
            }
            sqlite3_finalize(statement);
            sqlite3_close(_contactDB);
        }
    }@catch (NSException *e) {
        NSLog(@"Exception : %s",sqlite3_errmsg(_contactDB));
    }
}
- (void) find:(id)sender {
    const char *dbpath = [_databasePath UTF8String];
    sqlite3_stmt    *statement;
    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
        NSString *querySQL = [NSString stringWithFormat:@"SELECT roll, age FROM STUDENT WHERE name=\"%@\"",txtName.text];
        const char *query_stmt = [querySQL UTF8String];
        if (sqlite3_prepare_v2(_contactDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *roll = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
                txtroll.text = roll;
                NSString *age = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
                sldAge.value = [age floatValue];
               NSLog(@"Match found");
            } else {
               NSLog(@"Match found");
                txtroll.text = @"";
                sldAge.value = 0.0;
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(_contactDB);
    }
}
Download the complete source code from here : Complete project

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.