2013-05-01 61 views
1

我是iphone開發新手。我想在表sqlite的行中存儲一個NSDictionary。 我GOOGLE了,發現很多結果,但它不適合我。如何在sqlite上添加NSDictionary表中的行數據庫

這是我的字典:

NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"24",@"id",@"Folder",@"name",@"300 MB",@"size", nil]; 

還我搜索這個網站,但我不明白,在類似職位的任何事情。 請解釋我更多關於添加(存儲)SQLite數據庫行中的NSDictionary。

+1

您需要對字典進行編碼(可能是'JSON'或'plist')並將其存儲在數據庫中。 – dreamlax 2013-05-01 07:04:32

+1

我的惡魔我可以將這個詞典編碼爲plist,但是如何將這個(plist)存儲在數據庫中? – estefan 2013-05-01 07:19:58

回答

3

您可以通過創建一個具有三列的表(使用create table query)來完成此操作。然後將這些對象從您的字典插入這些列(使用插入查詢)。

編輯:將數據插入使用查詢:

  NSString *query = [NSString stringWithFormat:@"insert into tablename (column1, column2,column3) values('%@','%@','%@')",[dic objectForKey:@"id"],[dic objectForKey:@"name"],[dic objectForKey:@"size"]]; 
      NSLog(@"query : %@",query); 
      [self executeQuery:query]; 

在.H類做一個源碼實例:

sqlite3 *database; and import: #import<sqlite3.h> 

在.M類作出補充這些方法:

-(NSString *) dataFilePath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSLog(@"PATH %@",[documentsDirectory stringByAppendingPathComponent:DatabaseName]); 
    return [documentsDirectory stringByAppendingPathComponent:DatabaseName]; 
} 

/*================================================================== 
       METHOD FOR INSERTING DATA IN DATABASE 
==================================================================*/ 
-(void)executeQuery:(NSString *)query 
{ 
    //NSLog(@"QUERY : %@",query); 

    sqlite3_stmt *statement; 
    if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) 
    { 
     if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK) 
     { 
      if (sqlite3_step(statement) != SQLITE_DONE) 
      { 
       sqlite3_finalize(statement); 
      } 
     } 
     else 
     { 
      NSLog(@"query Statement Not Compiled"); 
     } 

     sqlite3_finalize(statement); 
     sqlite3_close(database); 
    } 
    else 
    { 
     NSLog(@"Data not Opened"); 
    } 
} 

對於閱讀數據:

/*================================================================== 
METHOD FOR Fetching Data FROM DATABASE 
==================================================================*/ 
NSString *query = [NSString stringWithFormat:@"select * from table_name"]; 
NSMutableArray *tableData = [self fetchingDataFromTable:query]; 

//這裏表數據數組包含所有記錄

-(NSMutableArray *)fetchingDataFromTable:(NSString *)query; 
{ 
    NSLog(@"QUERY : %@",query); 

    NSString *[email protected]""; 
    NSMutableArray *returnArray = [NSMutableArray new]; 
    if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) 
    { 
     sqlite3_stmt *statement; 
     if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)==SQLITE_OK) 
     { 
      while(sqlite3_step(statement)==SQLITE_ROW) 
      { 
       NSMutableDictionary *temp= [NSMutableDictionary new]; 
       const char *s; 


       s=(char *)sqlite3_column_text(statement, 0); 
       if(s==NULL) 
       { 
        [email protected]""; 
       } 
       else 
       { 
        idToReturn =[NSString stringWithUTF8String:s]; 
       } 
       [temp setObject:idToReturn forKey:@"id"]; 

       s=(char *)sqlite3_column_text(statement, 1); 
       if(s==NULL) 
       { 
        [email protected]""; 
       } 
       else 
       { 
        idToReturn =[NSString stringWithUTF8String:s]; 
       } 
       [temp setObject:idToReturn forKey:@"name"]; 

       s=(char *)sqlite3_column_text(statement, 2); 
       if(s==NULL) 
       { 
        [email protected]""; 
       } 
       else 
       { 
        idToReturn =[NSString stringWithUTF8String:s]; 
       } 
       [temp setObject:idToReturn forKey:@"size"]; 

       if (temp != nil) 
       { 
        [returnArray addObject:temp]; 

        temp = nil; 
       } 

      } 
      sqlite3_finalize(statement); 
      sqlite3_close(database); 
     } 
    } 
    return returnArray; 

} 

希望它可以幫助你。

+0

謝謝你親愛的朋友。我創建了帶有三列名稱(id,名稱,大小)和這個級別的表格數據庫,我做了什麼?你能解釋我更多關於(使用插入查詢)與代碼!非常感謝你。 – estefan 2013-05-01 07:18:09

+0

我編輯了我的答案。 – 2013-05-01 07:30:02

+0

我的朋友,我給這個錯誤「查詢語句不編譯」爲什麼? – estefan 2013-05-01 07:57:40

1

通過這個Link,在這裏你會得到一個很好的例子

0
- (NSMutableDictionary *)executeQuery:(NSString *)query 
{ 
     sqlite3_stmt *stmt; 
     const char *tail; 
     sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, &tail); 
     if (stmt == NULL) 
       return nil; 

     int status; 
     int num_cols; 
     int i; 
     int j = 1; 
     int type; 
     id obj; 
     NSString *key; 
     NSMutableArray *result; 
     NSMutableDictionary *row,*roww; 
     j = 0; 
     result = [NSMutableArray array]; 
     roww = [NSMutableDictionary dictionary]; 
     while ((status = sqlite3_step(stmt)) != SQLITE_DONE) { 

       if (status != SQLITE_ROW) 
       { 

         continue; 
       } 
       else 
       { 
       row = [NSMutableDictionary dictionary]; 
       num_cols = sqlite3_data_count(stmt); 
       for (i = 0; i < num_cols; i++) { 
         obj = nil; 
         type = sqlite3_column_type(stmt, i); 
         switch (type) { 
         case SQLITE_INTEGER: 
           obj = [NSNumber numberWithLongLong:sqlite3_column_int64(stmt, i)]; 
           break; 
         case SQLITE_FLOAT: 
           obj = [NSNumber numberWithDouble:sqlite3_column_double(stmt, i)]; 
           break; 
         case SQLITE_TEXT: 
           obj = [NSString stringWithUTF8String:sqlite3_column_text(stmt, i)]; 
           break; 
         case SQLITE_BLOB: 
           obj = [NSData dataWithBytes:sqlite3_column_blob(stmt, i) 
            length:sqlite3_column_bytes(stmt, i)]; 
           break; 
         case SQLITE_NULL: 
           obj = [NSNull null]; 
           break; 
         default: 
           break; 
         } 

         key = [NSString stringWithUTF8String:sqlite3_column_name(stmt, i)]; 
         [row setObject:obj forKey:key]; 
       } 

      NSString *keyq = [NSString stringWithFormat:@"%d",j]; 
      [roww setObject:row forKey:keyq]; 
      j++; 
        [roww setValue:@"1" forKey:@"Success"]; 

     } 

     } 
    sqlite3_finalize(stmt); 

    // NSLog(@"%@",roww); 
    return roww; 
} 
0
and get data into dictionary from table in ios 


-(void)getData:(NSString *) tablename 
{ 


    NSMutableDictionary * tabledata= [[NSMutableDictionary alloc] init]; 
    NSString *str = @"select * from "; 
    NSString *strQuary = [str stringByAppendingString:tablename]; 
    tabledata = [db executeQuery:strQuary]; 

    NSDictionary *dic = [tabledata valueForKey:@"0"]; 
    NSLog(@"dic is:%@",dic); 

} 
0

我已經創建動態代碼將返回所有列的列表包含所有行

-(NSMutableDictionary*)getRowsFromTableName:(NSString*)tableName 
{ 
NSString *databasePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] 
//       stringByAppendingPathComponent: @"sqlcipher.db"]; 
sqlite3 *db; 
bool sqlcipher_valid = NO; 
NSMutableDictionary *dbData = [[NSMutableDictionary alloc]init]; 
NSMutableArray *columnList = [[NSMutableArray alloc]init]; 

if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK) { 
    const char* key = [keyString UTF8String]; 
    sqlite3_key(db, key, strlen(key)); 
    if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) { 
     if(sqlite3_prepare_v2(db, "PRAGMA cipher_version;", -1, &stmt, NULL) == SQLITE_OK) { 
      if(sqlite3_step(stmt)== SQLITE_ROW) { 
       const unsigned char *ver = sqlite3_column_text(stmt, 0); 
       if(ver != NULL) { 
        sqlcipher_valid = YES; 

        // password is correct (or database initialize), and verified to be using sqlcipher 
        char *errMsg; 
        const char *query = [[NSString stringWithFormat:@"select * from %@",tableName] UTF8String]; //where name = 'abc'"; 
        if (sqlite3_exec(db, query, NULL, NULL, &errMsg) 
         != SQLITE_OK) 
        { 
         // isSuccess = NO; 
         NSLog(@"Failed to open data into table"); 
         [dbData setValue:@"Failed to open data into table" forKey:@"Message"]; 
         [dbData setValue:@"Failed" forKey:@"status"]; 
         return dbData; 
        } 
        else 
        { 
         NSLog(@"Data open Successfully"); 
         int num_cols; 
         if(sqlite3_prepare_v2(db, query, -1, &stmt, NULL) == SQLITE_OK) { 

          while (sqlite3_step(stmt) == SQLITE_ROW) 
          { 
           num_cols = sqlite3_data_count(stmt); 
           NSMutableDictionary *columnDic = [[NSMutableDictionary alloc]init]; 
           for (int i = 1; i < num_cols; i++) { 
            NSString *colValue = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, i)]; 
            NSString *colName = [NSString stringWithUTF8String:(char*)sqlite3_column_name(stmt, i)]; 
            [columnDic setValue:colValue forKey:colName]; 
            NSLog(@"%@",columnDic); 
           } 
           [columnList addObject:columnDic]; 
           columnDic = nil; 
          } 
          NSLog(@"%@",columnList); 
          [dbData setValue:columnList forKey:@"data"]; 

         } 
        } 
       } 
      } 
      else 
      { 
       NSLog(@"Error while binding variable. '%s'", sqlite3_errmsg(db)); 
       [dbData setValue:[NSString stringWithFormat:@"Error while binding variable. '%s'", sqlite3_errmsg(db)] forKey:@"Message"]; 
       [dbData setValue:@"Failed" forKey:@"status"]; 
       return dbData; 
      } 
      sqlite3_finalize(stmt); 
     } 
     else 
     { 
      NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(db)); 
      [dbData setValue:[NSString stringWithFormat:@"Error while creating update statement. '%s'", sqlite3_errmsg(db)] forKey:@"Message"]; 
      [dbData setValue:@"Failed" forKey:@"status"]; 
      return dbData; 
     } 
    } 
    else 
    { 
     NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(db)); 
     [dbData setValue:[NSString stringWithFormat:@"Error while creating update statement. '%s'", sqlite3_errmsg(db)] forKey:@"Message"]; 
     [dbData setValue:@"Failed" forKey:@"status"]; 
     return dbData; 
    } 
    sqlite3_close(db); 
} 
NSLog(@"%@",dbData); 

return dbData; 

}

相關問題