siddle
siddle

Reputation: 137

SQlite insert data in iOS App

I'm following some tutorials from youtube for sqlite crud operations. I have textfields with name, contact and address , when i hit save button it show message in console that data is saved but when i look at database it nothing appears there. My database path is correct and no errors in code but 'm confused why it isn't going. My path code is this,

-(void)copyandpaste{
NSArray *arr1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *str1 = [arr1 objectAtIndex:0];
strpath = [str1 stringByAppendingPathComponent:@"personinfo.sqlite"];

if (![[NSFileManager defaultManager]fileExistsAtPath:strpath]) {
    NSString *local = [[NSBundle mainBundle]pathForResource:@"personinfo" ofType:@"sqlite"];
    [[NSFileManager defaultManager]copyItemAtPath:local toPath:strpath error:nil];
}
NSLog(@"%@",strpath);
}

this method is called in appdelegate.m file,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self copyandpaste];
return YES;
}

I have mad NSObject class for database connection. the connection code is this,

-(id)init{
appdel = (AppDelegate *)[[UIApplication sharedApplication]delegate]; //get all methods in AppDelegate
strmain = appdel.strpath;
return self;
}

-(NSMutableArray *)getalluser:(NSString *)query{

arrdata = [[NSMutableArray alloc]init];

if (sqlite3_open([strmain UTF8String], &(database))==SQLITE_OK) {
    sqlite3_stmt *connection;
    if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK) {
        while (sqlite3_step(connection)==SQLITE_ROW) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];

            NSString *str12 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 0)];  //name in first column

            NSLog(@"Checking");

            NSString *str13 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 1)];  //contact in second column

             NSString *str14 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 2)]; //address in third column

            [dic setObject:str12 forKey:@"name"];
            [dic setObject:str13 forKey:@"contact"];
            [dic setObject:str14 forKey:@"address"];
            [arrdata addObject:dic];
        }
    }

    sqlite3_finalize(connection);
}
sqlite3_close(database);
return arrdata;
}

My save button code with query is this,

- (IBAction)btnSave:(id)sender {


NSString *saveDATA=[[NSString alloc]initWithFormat:@"insert into stuInfo values('%@','%@','%@')",txtName,txtContact,txtAddress];

dboperations *db = [[dboperations alloc ]init];
BOOL ds = [db getalluser:saveDATA];

if (ds) {
    NSLog(@"Data Saved in database");
}else{
     NSLog(@"Data is not Saved in database");
}
}

Upvotes: 0

Views: 63

Answers (2)

Neeraj Sonaro
Neeraj Sonaro

Reputation: 346

 - (NSString*) saveData:(NSString *)name cont:(NSString *)contacts  add:(NSString *)address
    {
const char *dbpath = [YOUR_DATA_BASE_PATH UTF8String];

if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
    NSLog(@"=============saveData open==============");
    const char * query="insert into YOUR_TABLE_NAME(name,contacts,address) values(?,?,?);";

    sqlite3_stmt *inset_statement;

    char *errMsg;

    if (sqlite3_open(dbpath, &database)!=SQLITE_OK) {
        NSLog(@"Error to Open");
        return nil;
    }

    if (sqlite3_prepare_v2(database, query , -1,&inset_statement, NULL) != SQLITE_OK )
    {
        NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(database), sqlite3_errcode(database));
        NSLog(@"Error to Prepare");
        return nil;
    }
    //No of data to insert
    sqlite3_bind_text(inset_statement,1,[name  UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(inset_statement,2,[contacts  UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(inset_statement,3,[address  UTF8String], -1, SQLITE_TRANSIENT);


    if(sqlite3_step(inset_statement)== SQLITE_DONE)
    {
        long long lastRowId = sqlite3_last_insert_rowid(database);
        NSString *rowId = [NSString stringWithFormat:@"%d", (int)lastRowId];
        NSLog(@"Row ID of Last Inserted row %@",rowId);
        sqlite3_finalize(inset_statement);
        sqlite3_close(database);
        NSLog(@"=============saveData Close==============");
        return rowId;
    }
    if (sqlite3_exec(database, query, NULL, NULL, &errMsg)
        != SQLITE_OK)
    {
     NSLog(@"Failed to Insert msg in message table Error = %s",errMsg);
          sqlite3_finalize(inset_statement);
          sqlite3_close(database);
          NSLog(@"=============saveData Close==============");
          return nil;
       }
          else
           {
            sqlite3_finalize(inset_statement);
            }
          }

          NSLog(@"=============saveData Close==============");
          sqlite3_close(database);
          return nil;
          }

Upvotes: 2

Flexicoder
Flexicoder

Reputation: 8501

You are not handling if there are any errors in the SQLite statements you are preparing.

The function will always return true because arrdata is never null

You need to add anelse statements to your if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK)

to show any errors...

NSLog(@"%s",sqlite3_errmsg(database));

Upvotes: 0

Related Questions