-1

我想在我的应用程序中使用 SQLite 来插入和显示我们在 SQLite 中创建的表中的数据,我是 SQLite 的新手,所以在谷歌搜索时我遇到了链接http://www.techotopia.com/index.php/ An_Example_SQLite_based_iPhone_Application帮助我插入和显示这样的数据(我已将 URL 更改为示例 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

现在我想要的是在 viewDidLoad 方法中,如果它不存在,我们正在创建表,我们使用命令“创建”表,所以我想动态地创建创建表命令并改变属性,比如我们选择创建表仅使用名称,如果我们选择仅使用名称和编号创建表,或者如果我们选择创建具有多于这两个属性的表,则命令应相应更改。

4

1 回答 1

4

创建一个单独的方法来创建表并使用不同的属性调用该方法。

- (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];
 }
于 2012-12-03T06:57:00.703 回答