2012-07-05 4 views
0

Dans mon application, j'utilise la base de données SQLite pour stocker des données. Voici l'exemple de code am utilise pour insérer des donnéesinsertion de données dans la table DB SQLite

dans ma classe principale en appelle ces méthodes comme suit

-(IBAction)insertButtonAction:(id)sender 
{ 
BOOL isRollNum; 
Database *db = [[Database alloc]init]; 
if ([rollNumberTxtFld.text length]>0) 
{ 
    isRollNum = [db checkForRollNumber:rollNumberTxtFld.text]; 
    if (isRollNum == YES) 
    { 
     UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Student with specified roll number already available" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
     [errorAlert show]; 
    } 
    else 
    { 
     if ([nameTxtFld.text length]>0 && [rollNumberTxtFld.text length]>0 ) 
     { 
      NSString *name = nameTxtFld.text; 
      NSString *num = rollNumberTxtFld.text; 
      int age = [ageTxtFld.text intValue]; 
      NSString *address1 = address1TxtFld.text; 
      NSString *address2 = address2TxtFld.text; 
      NSString *mobile = mobileTxtFld.text; 
      NSString *class =classTxtFld.text; 

      NSLog(@"%@ %@ %d %@ %@ %@ %@ ",name,num,age,address1,address2,mobile,class); 

      NSString* insert_stmt = NULL; 
      insert_stmt = [NSString stringWithFormat:@"insert into friends(name,rollnumber,age,address1,address2,mobile,class) values('%@', '%@', '%d', '%@', '%@', '%@', '%@')",name,num,age,address1,address2,mobile,class,nil ]; 
      Database *db = [[Database alloc]init]; 
      BOOL inserted = [db insertIntoDB:insert_stmt]; 
      if (inserted == YES) 
      { 
       insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Inserted" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
       [insertReenterAlert show]; 
      } 
      else 
      { 
       insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Not Inserted" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
       [insertReenterAlert show]; 
      } 
     } 
     else 
     { 
      insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@" Please enter required fields and try again." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
      [insertReenterAlert show]; 
     } 
    } 
} 
else 
{ 
    insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@" Please enter required fields and try again." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
    [insertReenterAlert show]; 
} 
} 

Cette méthode permet de vérifier si le numéro de rouleau que nous voulons insérer est déjà là ou pas dans la table DB.

-(BOOL)checkForRollNumber:(NSString *) num 
{ 
rollNumberArray = [[NSMutableArray alloc] init]; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
dbPath = [[NSBundle mainBundle]pathForResource:@"FriendsList"ofType:@"sqlite"]; 
NSLog(@"dbPath %@",dbPath);  
BOOL success = [fileManager fileExistsAtPath:dbPath]; 
int rowCount = 0; 
if (success) 
{ 
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) 
    { 
     const char* sqlStatement = "SELECT COUNT(rollnumber) FROM friends "; 
     sqlite3_stmt* statement; 
     if(sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK) 
     { 
      if(sqlite3_step(statement) == SQLITE_ROW) 
      rowCount = sqlite3_column_int(statement, 0); 
     } 
     else 
     { 
      NSLog(@"Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(database)); 
     } 
     sqlite3_finalize(statement); 
     sqlite3_close(database); 
    } 
} 
NSLog(@"rowCount %d",rowCount); 
if (success) 
{ 
    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) 
    { 
     const char *selectSQL = "SELECT rollnumber FROM friends"; 
     sqlite3_stmt *statement; 
     if (sqlite3_prepare_v2(database, selectSQL, -1, &statement, NULL) == SQLITE_OK) 
     { 
      while (sqlite3_step(statement) == SQLITE_ROW) 
      { 
       for (int i=0; i<rowCount; i++) 
       { 
        NSLog(@"i %d",i); 
        NSString *str = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)]; 
        [rollNumberArray addObject:str]; 
        NSLog(@"rollNumberArray: %@",[rollNumberArray objectAtIndex:i]); 
       } 
      } 
      for (int i=0; i<[rollNumberArray count]; i++) 
      { 
       NSLog(@"[rollNumberArray objectAtIndex:%d] %@ == num %@",i,[rollNumberArray objectAtIndex:i],num); 
       if ([[rollNumberArray objectAtIndex:i] intValue] == [num intValue]) 
       { 
        NSLog(@"FOUND"); 
        return YES; 
       } 
       else 
       { 
        NSLog(@"NOT FOUND"); 
        return NO; 
       } 
      } 
     } 
     else 
     { 
      NSLog(@"Statement Not Prepared"); 
      return NO; 
     } 
     sqlite3_finalize(statement); 
    } 
    else 
    { 
     NSLog(@"Database Not Opened"); 
     return NO; 
    } 
    sqlite3_close(database); 
} 
else 
{ 
    NSLog(@"File Not Opened"); 
    return NO; 
} 
} 

Ceci est la méthode pour insérer des données dans la table

-(BOOL) insertIntoDB :(NSString *) insert_stmt 
{ 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
dbPath = [[NSBundle mainBundle]pathForResource:@"FriendsList"ofType:@"sqlite"]; 
NSLog(@"dbPath %@",dbPath);  
BOOL success = [fileManager fileExistsAtPath:dbPath]; 
if (success) 
{ 
    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) 
    { 
     const char *insertSQL = [insert_stmt UTF8String]; 
     sqlite3_stmt *statement; 
     if (sqlite3_prepare_v2(database, insertSQL, -1, &statement, NULL) == SQLITE_OK) //**Always not entering into this if** 
     { 
      if (sqlite3_step(statement) == SQLITE_DONE) 
      { 
       NSLog(@"Succesfully added in DB"); 
       return YES; 
      } 
      else 
      { 
       NSLog(@"Not added in DB"); 
       return NO; 
      } 
     } 
     else 
     { 
      NSLog(@"Statement Not Prepared"); 
      return NO; 
     } 
     sqlite3_finalize(statement); 
    } 
    else 
    { 
     NSLog(@"Database Not Opened"); 
     return NO; 
    } 
    sqlite3_close(database); 
} 
else 
{ 
    NSLog(@"File Not Opened"); 
    return NO; 
} 
} 

Il ne satisfait pas cette condition sqlite3_prepare_v2 (base de données, SelectSQL, -1, déclaration &, NULL) == SQLITE_OK Et seules les premières valeurs sont ajoutées. Toute personne peut m'aider ou suggérer.

Merci d'avance.

+0

Vérifiez le chemin de votre base de données que vous affichez avec NSLOG, est-ce correct? –

+0

Envisagez d'utiliser CoreData? – Devraj

+0

Et que sqlite3_errmsg (base de données) signale-t-il lorsque votre préparation échoue? – Rob

Répondre

0

sqlite3_prepare_v2 renverra un code d'erreur que vous ignorez. Pourquoi ne pas l'affecter à une variable afin de pouvoir l'examiner avant de la tester avec l'instruction if?

int returnCode = sqlite3_prepare_v2(database, insertSQL, -1, &statement, NULL) 
if (returnCode == SQLITE_OK) // put a breakpoint here and look at return code. 
+0

Je vérifie que l'un d'eux aussi –

+0

Mais qu'est-ce que ça rend? Ce code d'erreur devrait vous indiquer pourquoi votre préparation échoue. –

Questions connexes