2016-05-06 8 views
0
-(BOOL)createDB{ 
NSString *docsDir; 
NSArray *dirPaths; 
dirPaths = NSSearchPathForDirectoriesInDomains 
(NSDocumentDirectory, NSUserDomainMask, YES); 
docsDir = dirPaths[0]; 
databasePath = [[NSString alloc] initWithString: 
       [docsDir stringByAppendingPathComponent: @"oiwii.db"]]; 
BOOL isSuccess = YES; 
NSFileManager *filemgr = [NSFileManager defaultManager]; 
if ([filemgr fileExistsAtPath: databasePath ] == NO) 
{ 
    const char *dbpath = [databasePath UTF8String]; 
    if (sqlite3_open(dbpath, &database) == SQLITE_OK) 
    { 
     char *errMsg; 
     const char *sql_stmt ="create table if not exists jsonData (status text, message text, mood_name text, description text, c1 text, c2 text c3 text, c4 text, c5 text, font_name text, font_size text, font_color text)"; 
     if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!= SQLITE_OK) 
     { 
      isSuccess = NO; 
      NSLog(@"Failed to create table"); 
     } 
     sqlite3_close(database); 
     return isSuccess; 
    } 
    else { 
     isSuccess = NO; 
     NSLog(@"Failed to open/create database"); 
    } 
} 
return isSuccess; 

}wie einfügen und json Array in SQLite ios

i eine Datenbank erstellt haben, speichern oben und ich versuche, das JSON-Objekt (Array) in meine SQLite hinzuzufügen. mein JSON-Objekt sieht so aus - {"Stimmungen_Name": "Stimmungs2", "Beschreibung": "Das ist Stimmung 2", "C1": "D4FF38", "C2": "FFA83D", "C3": " FFFA9E "," c4 ":" 66FFBA "," c5 ":" 63FFE8 "," font_name ":" Standard "," font_size ":" 10 "," font_color ":" 363636 "} und ich möchte das holen

Array
-(BOOL)saveData:(NSString *)status message:(NSString *)message mood_name:(NSString *)mood_name description:(NSString *)description c1:(NSString *)c1 c2:(NSString *)c2 c3:(NSString *)c3 c4:(NSString *)c4 c5:(NSString *)c5 font_name:(NSString *)font_name font_size:(NSString *)font_size font_color:(NSString *)font_color{ 

const char *dbpath = [databasePath UTF8String]; 
if (sqlite3_open(dbpath, &database) == SQLITE_OK) 
{ 
    NSString *insertSQL = [NSString stringWithFormat:@"insert into jsonData (status,message, description, c1,c2,c3,c4,c5,font_name,font_size,font_color) values (\"%@\",\"%@\", \"%@\", \"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",status, message, description, c1,c2,c3,c4,c5,font_name,font_size,font_color]; 
    const char *insert_stmt = [insertSQL UTF8String]; 
    sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL); 
    if (sqlite3_step(statement) == SQLITE_DONE) 
    { NSLog(@"data saved"); 
     return YES; 

    } 
    else { 
     return NO; 
    } 

} 

sqlite3_reset(statement); 
return NO; 

}

Update: Code, um Daten abzurufen

-(void)fetchdata 
{ 
arrayfetched = [[NSMutableArray alloc] init]; 

// Setup the database object 
sqlite3 *database; 

// Open the database from the users filessytem 
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
{ 

    //SQLIte Statement 
    NSString *sqlStatement_userInfo =[NSString stringWithFormat:@"Select * from moodsdata"]; 

    sqlite3_stmt *compiledStatement; 


    if(sqlite3_prepare_v2(database, [sqlStatement_userInfo UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) 
    { 

     // Loop through the results and add them to the fetchedarray 
     while(sqlite3_step(compiledStatement) == SQLITE_ROW) 
     { 
      // Init the Data Dictionary 
      NSMutableDictionary *_dataDictionary=[[NSMutableDictionary alloc] init]; 

      NSString *msg = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; 

      NSString *status = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; 

      NSString *data = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; 

      [_dataDictionary setObject:[NSString stringWithFormat:@"%@",msg] forKey:@"message"]; 
      [_dataDictionary setObject:[NSString stringWithFormat:@"%@",status] forKey:@"status"]; 
      [_dataDictionary setObject:[NSString stringWithFormat:@"%@",data] forKey:@"data"]; 

      [arrayfetched addObject:_dataDictionary]; 
      NSLog(@"array fetched%@",arrayfetched); 

     } 
    } 
    else 
    { 
     NSLog(@"No Data Found"); 
    } 

    // Release the compiled statement from memory 
    sqlite3_finalize(compiledStatement); 
} 
    sqlite3_close(database); 
NSLog(@" fetched array%@",arrayfetched); 
} 

mir bitte helfen.

+0

Was ist das Problem Sie konfrontiert sind? –

+0

Ich weiß nicht, wie man JSON-Array in SQLite speichern Daten Methode speichern. Ich habe eine andere Klasse für die Datenbank –

+0

und wo ich json rufe diese Klasse ist anders. so, wie diese JSON-Daten in SQLite einfügen –

Antwort

0

versuchen, diese Methode in der Datenbank zu speichern. VORBEREITETE STATEMENTS SIND BESSER ALS NORMAL INSERT QUERY.

-(BOOL) saveApiResults: (NSString *)tableName : (NSArray *)data { 
    //assign false value to saveSuccess 
    BOOL saveSuccess = NO; 

    sqlite3 *database; 
    @try { 
     //get database path 
     const char *dbPath = [YOUR_DB_PATH UTF8String]; 
     if(sqlite3_open(dbPath,&database)==SQLITE_OK) { 

      sqlite3_exec(database, "BEGIN", 0, 0, 0); 

      NSDictionary *rowData=[data objectAtIndex:0]; 
      //convert the string into array 
      NSArray *keyArray = [rowData allKeys]; 

      NSString *[email protected]"INSERT OR REPLACE INTO "; 
      insertSQL=[insertSQL stringByAppendingString:tableName]; 
      insertSQL=[insertSQL stringByAppendingString:@" VALUES("]; 
      for(int j=0;j<[keyArray count];j++) 
      { 
       insertSQL=[insertSQL stringByAppendingString:@"?"]; 
       if(j<[keyArray count]-1) 
        insertSQL=[insertSQL stringByAppendingString:@","]; 
      } 
      insertSQL=[insertSQL stringByAppendingString:@");"]; 


      NSLog(@"query : %@ ",insertSQL); 

      const char *sqlstatement = [insertSQL UTF8String]; 

      sqlite3_stmt *compiledstatement; 

      if(sqlite3_prepare_v2(database,sqlstatement , -1, &compiledstatement, NULL)==SQLITE_OK) { 

       //fetch the dictionary(key,value) from the array of api result 
       for (NSUInteger i = 0; i < [data count]; i++) { 
        NSDictionary *rowData=[data objectAtIndex:i]; 

        //get the value for ech key from api response and execute the insert statement 
        for(int j=0;j<[keyArray count];j++) { 
         NSString *val = @""; 
         NSString *value=(NSString *)[rowData objectForKey:[keyArray objectAtIndex:j]]; 
         if((value != nil) && (![value isEqual:[NSNull null]])) 
          val=[NSString stringWithFormat:@"%@",value]; 

         sqlite3_bind_text(compiledstatement,j+1,[val UTF8String], -1, SQLITE_TRANSIENT); 
        } 

        if(sqlite3_step(compiledstatement) != SQLITE_DONE) { 
         NSLog(@"ERROR"); 
        } 

        sqlite3_clear_bindings(compiledstatement); 
        sqlite3_reset(compiledstatement); 


       } 

       sqlite3_exec(database, "COMMIT", 0, 0, 0); 
       saveSuccess = YES; 
       NSLog(@"RESULTS SAVED SUCCESSFULLY!"); 
      } else { 
       NSLog(@"Statement FAILED (%s)", sqlite3_errmsg(database)); 
      } 

      sqlite3_finalize(compiledstatement); 

     } else { 
       NSLog(@"Statement FAILED (%s)", sqlite3_errmsg(database)); 
     } 
    } 
    @catch (NSException *exception) { 
     NSLog(@"NSException : %@",exception.description); 
    } 
    @finally { 
     sqlite3_close(database); 
    } 

    //return data save status 
    return saveSuccess; 
} 

Und hier Ihre JSON Antwort analysieren und die NSArray von NSDictionary Objekte zu saveApiResults Methode senden.

-(void) saveJSONData { 
    NSData* jsonData = [YOUR_JSON_RESPONSE dataUsingEncoding:NSUTF8StringEncoding]; 

    NSError *error = nil; 
    NSDictionary *responseObj = [NSJSONSerialization 
           JSONObjectWithData:jsonData 
           options:0 
           error:&error]; 

    if(! error) { 
     NSArray *responseArray = [responseObj objectForKey:@"data"]; 

     [self saveApiResults : YOUR_TABLE_NAME : responseArray]; 
    } else { 
     NSLog(@"Error in parsing JSON"); 
    } 
} 

//-Code, um Ihre Ergebnisse

-(NSMutableArray *)getQueryResult { 

    //get the database path 
    const char *dbpath = [databasePath UTF8String]; 

    sqlite3 *DB; 
    NSMutableArray *results=[[NSMutableArray alloc] init]; 

    @try { 
     sqlite3_stmt *statement; 
     NSMutableDictionary *dict; 

     if (sqlite3_open(dbpath, &DB) == SQLITE_OK) { 

      //sql select query 
      NSString *querySQL = [NSString stringWithFormat: @"SELECT * from moodsdata"]; 

      const char *query_stmt = [querySQL UTF8String]; 

      if (sqlite3_prepare_v2(DB, query_stmt, -1, &statement, NULL) == SQLITE_OK){ 

       if(sqlite3_step(statement) == SQLITE_ROW) { 
        do { 
         dict = [[NSMutableDictionary alloc] init]; 

         const unsigned char *msg = sqlite3_column_text(statement, 0); 

         const unsigned char *status = sqlite3_column_text(statement, 1); 

         const unsigned char *data = sqlite3_column_text(statement, 2); 

         [dict setValue:[NSString stringWithFormat:@"%s",msg] forKey:@"message"]; 
         [dict setValue:[NSString stringWithFormat:@"%s",status] forKey:@"status"]; 
         [dict setValue:[NSString stringWithFormat:@"%s",data] forKey:@"data"]; 

         //add dictionary(key,value) to the array 
         [results addObject:dict]; 
        } 

        while (sqlite3_step(statement) == SQLITE_ROW); 
       } else { 
        NSLog(@"Statement FAILED (%s)",sqlite3_errmsg(DB)); 
       } 

      } else { 
       NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(DB)); 
      } 

      sqlite3_finalize(statement); 
     } else { 
      NSLog(@"Can not open DB : %s",sqlite3_errmsg(DB)); 
     } 

    } 
    @catch (NSException *exception) { 
     NSLog(@"NSException : %@",exception.description); 
    } 
    @finally { 
     sqlite3_close(DB); 
    } 

    //return the database results 
    return results; 
} 

zu holen // Wie Sie die Ergebnisse von getQueryResults verwenden

-(void) showData { 
    NSMutableArray *results = [self getQueryResult]; 
    for (NSMutableDictionary *resultDic in results) { 
     NSString *msg = [resultDic objectForKey:@"message"]; 
     NSString *status = [resultDic objectForKey:@"status"]; 
     NSString *data = [resultDic objectForKey:@"data"]; 

     NSLog(@"Result : %@ : %@ : %@",msg,status,data); 
    } 
} 
+0

@AmrutGaikwad Willkommen Kumpel. – Microprocessor8085

+0

@AmrutGaikwad Hey Kumpel, Bitte akzeptieren Sie die Antwort. – Microprocessor8085

+0

@AmrutGaikwad entfernen if (DATABASE_DEBUG_MODE_FLAG) Kumpel. Dies ist nur eine zusätzliche benutzerdefinierte BOOL-Konstante. Keine Notwendigkeit von diesem hier. – Microprocessor8085

0

Sie können eine Klasse erstellen, in der alle datenbankbezogenen Arbeiten ausgeführt werden. Rufen Sie diese bestimmte Methode aus dieser Klasse an beliebiger Stelle in Ihrem Projekt auf, um Daten aus der Datenbank einzufügen, zu aktualisieren oder zu löschen.

können Sie diesen Link für weitere Informationen und Anleitung siehe: this

+0

danke für den Vorschlag. –