Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8955911
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T14:39:48+00:00 2026-06-15T14:39:48+00:00

i want to use the SQLite in my app to insert and display the

  • 0

i want to use the SQLite in my app to insert and display the data from the tables we created in SQLite , i am new to SQLite so while googling i came across the link http://www.techotopia.com/index.php/An_Example_SQLite_based_iPhone_Application which help me for inserting and displaying the data like this (i have changed the URL to sample URL)

#import "MasterViewController.h"

#import "DetailViewController.h"

@interface MasterViewController () 
{
    NSMutableArray *_objects;
}
@end

@implementation MasterViewController

@synthesize detailViewController = _detailViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Master", @"Master");
    }
    return self;
}

- (void)viewDidLoad
{
    NSString *docsDir;
    NSArray *dirPaths;
    alertFlg=1;

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];

    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 CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table") ;
            }
            sqlite3_close(contactDB);
        }
        else 
        {
               NSLog(@"Failed to open/create database") ;
        }
    }

    [super viewDidLoad];

    namearry = [[NSMutableArray alloc] init];
    costarry   = [[NSMutableArray alloc] init];
    discrarry  = [[NSMutableArray alloc] init];

    [self parseXMLFileAtURL:@"http://api.androidhive.info/pizza/?format=xml"];

    [self saveData];
    [self displayData];

}
- (void)saveData
{

    sqlite3_stmt    *statement;

    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        int i;
        for ( i=0; i<[namearry count]; i++) {
            NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CONTACTS (name) VALUES ( \"%@\")", [namearry objectAtIndex:i]];

                                   const char *insert_stmt = [insertSQL UTF8String];

                                   sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
                                   if (sqlite3_step(statement) == SQLITE_DONE)
                                   {
                                       NSLog(@"Contact added");

                                   } else {
                                       NSLog(@"Failed to add contact") ;
                                   }
                                   sqlite3_finalize(statement);
        }
        sqlite3_close(contactDB);
    }
}

-(void)displayData
{
    const char *dbpath = [databasePath UTF8String];
    sqlite3_stmt    *statement;

    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM contacts "];

        const char *query_stmt = [querySQL UTF8String];

        if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *nameField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];

                [namearry addObject:nameField];
                NSLog(@"Match found");
            }
                     sqlite3_finalize(statement);
        }
    }
     sqlite3_close(contactDB);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [namearry count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    }

    cell.textLabel.text = [namearry objectAtIndex:indexPath.row];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   /* if (!self.detailViewController) {
        self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    }
    NSDate *object = [_objects objectAtIndex:indexPath.row];
    self.detailViewController.detailItem = object;
    [self.navigationController pushViewController:self.detailViewController animated:YES];*/
}

/*------------------------------------Parser's Code-----------------------------------------*/
-(void) parseXMLFileAtURL:(NSString *)URL
{
//    NSURL *url1=@"http://api.androidhive.info/pizza/?format=xml";
    feedParser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:URL]];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [feedParser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [feedParser setShouldProcessNamespaces:NO];
    [feedParser setShouldReportNamespacePrefixes:NO];
    [feedParser setShouldResolveExternalEntities:NO];
    [feedParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{       
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    if (alertFlg==1) 
    {
        alertFlg=0;
        NSString * errorString = [NSString stringWithFormat:@"Network Error", [parseError code]];
        UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Please check the internet connection" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];
       // [errorAlert release];
    }
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{           
    currentElement =[elementName copy];
    if ([elementName isEqualToString:@"name"]) 
    {
        //namearry=[[NSMutableArray alloc] init];
        nameStrng =[[NSMutableString alloc] init];
    }
    else if ([elementName isEqualToString:@"cost"]) 
    {
        //costarry=[[NSMutableArray alloc] init];
        costStrng =[[NSMutableString alloc] init];
    }
    else if ([elementName isEqualToString:@"description"]) 
    {
        //discrarry=[[NSMutableArray alloc] init];
        descpStrng =[[NSMutableString alloc] init];
    }

}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
    if ([elementName isEqualToString:@"name"]) 
    {
        nameStr=nameStrng;
      //  NSLog(@"namestr:=%@",nameStrng);
        [namearry addObject:nameStrng];
    }
    else if ([elementName isEqualToString:@"cost"]) 
    {
        costStr=costStrng;
        [costarry addObject:costStrng];
    }
    else if ([elementName isEqualToString:@"description"]) 
    {
        descrpStr=descpStrng;
        [discrarry addObject:descpStrng];
    }

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([currentElement isEqualToString:@"name"]) 
    {
       // NSLog(@"appending string for name attribute:=%@",string);
        [nameStrng appendString:string];
    }
    else if ([currentElement isEqualToString:@"cost"]) 
    {
        [costStrng appendString:string];
    }
    else if ([currentElement isEqualToString:@"description"]) 
    {
        [descpStrng appendString:string];
    }

}
- (void)parserDidEndDocument:(NSXMLParser *)parser 
{

}

/*----------------------End Of The Parser's Code AND Start Of the TableView'S Code---------------------------*/
@end

Now what i want is in viewDidLoad method we are creating the table if it doesn’t exist, we used the command “create” table, so i want to make that create table command dynamically with changing attributes like if we choose to create the table with name only, if we choose to create the table with name and number only or if we choose to create the table with more than this two attributes then the command should change accordingly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T14:39:49+00:00Added an answer on June 15, 2026 at 2:39 pm

    Create a separate method to create table and call that method using different attributes.

    - (void)viewDidLoad
      {
         NSString *idField = @"ID INTEGER PRIMARY KEY AUTOINCREMENT";
         NSString *nameField = @"NAME TEXT";
         NSString *ageField = @"AGE INTEGER";
    
         // Make the field array using different attributes in different cases
         NSArray *fieldArray = [NSArray arrayWithObjects:idField,nameField,ageField, nil];
    
        [self createTable:fieldArray];
    
      }
    
    - (void)createTable:(NSArray *)fieldArray
     {
        // Put all the code for create table and just change the query as given below
        NSString *queryString = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS CONTACTS (%@)",[fieldArray componentsJoinedByString:@","]];
        const char *sql_stmt = [queryString UTF8String];
     }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

all. I want to insert some initial data in db(sqlite) when it was created.
In my iPhone app, I use a sqlite table to hold my data. While
In my Android app, I want to use my existing sqlite database.I followed http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
I am starting a project from scratch in WPF using SQLite.I want to use
I am in mobile app. I use ajax calls to receive data from webserver
I am developing a mobile app. I use ajax calls to receive data from
I have created one app in iOS5. I want to store and retrive data
I want to get start with DayPilot control I do not use SQLite and
I have normal sqlite database and want to use fts3. As mentioned in http://www.sqlite.org/fts3.html
To speed up the unit tests I want to use SQLite instead of MySQL,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.