2012-12-03 19 views
-1

我想在我的應用程序中使用SQLite來插入和顯示我們在SQLite中創建的表中的數據,我是SQLite的新手,所以當谷歌搜索時,我遇到了鏈接http://www.techotopia.com/index.php/An_Example_SQLite_based_iPhone_Application,它可以幫助我插入和顯示數據這(我已經改變了URL來樣URL)如何使用爲SQLite創建的objective-c代碼使用alter table命令來插入diff。值

#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 *[email protected]"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方法中,我們正在創建的表,如果它不存在,我們使用命令「創造」的表,所以我想通過改變屬性來動態創建表命令,比如如果我們選擇僅用名字創建表,如果我們選擇僅創建名稱和數字表,或者如果我們選擇創建具有多於這兩個屬性的表,那麼命令應該相應地改變。

+0

我在viewDidLoad中使用SQLite創建表的話,我插在SQLite表中的數據保存數據,然後我讀的數據回displayData,我要的是使表的創建在viewDidLoad中每個時間改變每用戶選擇。我試着用差異。編碼邏輯,但它的發射沒有創建數據庫的sqlite錯誤 – iShwar

+0

是的,這是正確的,你不能創建新的數據庫,但你可以創建新的表,如@ Anusha的答案:) –

+0

而且它肯定一旦表說'聯繫'在那裏,那麼你不能創建相同的名稱表,即說'聯繫'。 –

回答

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]; 
} 
相關問題