2013-03-16 64 views
0

recordDict是一個NSMutableDictionary,其鍵與表的列名相同。iphone中的sqlite插入方法

-(void) insertRecord:(NSMutableDictionary *)recordDict tableName:(NSString *)table{ 

    @try { 

     if (sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK) { 

      NSMutableString *statement=[NSMutableString stringWithFormat:@"insert into %@ (",table]; 
      sqlite3_stmt *compiledStatement; 
      NSArray *keys=[recordDict allKeys]; 
      for (int i=0; i< [keys count]; ++i) { 
       [statement appendString:[keys objectAtIndex:i]]; 
       int j=i+1; 
       if (j == [keys count]) { 
        [statement appendString:@")"]; 
       } 
       else 
       { 
        [statement appendString:@","]; 
       } 
      } 
      [statement appendString:@" values ("]; 
      for (int i=0; i < [keys count]; ++i) { 
       [statement appendString:[recordDict objectForKey:[keys objectAtIndex:i]]]; 
       int j=i+1; 
       if (j == [keys count]) { 
        [statement appendString:@")"]; 
       } 
       else 
       { 
        [statement appendString:@","]; 
       } 
      } 

      const char *sqlstatement = [statement UTF8String]; 
      if (sqlite3_prepare_v2(database, sqlstatement, -1, &compiledStatement, NULL)== SQLITE_OK) 
      { 
       if (SQLITE_DONE!=sqlite3_step(compiledStatement)) 
       { 
        NSAssert1(0,@"Error when inserting %s",sqlite3_errmsg(database)); 
       } 
       else 
       { 
        //NSLog(@"Data inserted Successfully"); 
       } 
       //[recordDict release]; 
      } 
      else { 
       //NSLog(@"Failed with error"); 
       NSAssert1(0,@"Error when creation %s",sqlite3_errmsg(database)); 

      } 

     } 
     sqlite3_close(database); 
    } 
    @catch (NSException *exception) { 
     NSLog(@"Error info is %@",[exception description]); 
    } 

} 

此代碼給出了所需的結果並適用於任何表格。但我想要小代碼。誰能幫我?

回答

0
-(void)tableInsert:(NSString*)field1 Into:(NSString*)field2 intoTable:(NSString*)field3:(NSString*)field4 
{ 
char *err; 

NSString *sql=[NSString stringWithFormat:@"INSERT OR REPLACE INTO 'tablename' ('f1' , 'f2','f3','f4') VALUES ('%@','%@','%@','%@')",field1,field2,field3,field4]; 
NSLog(@"%@",sql); 
if(sqlite3_exec(db,[sql UTF8String], NULL, NULL, &err)!=SQLITE_OK) 
    { 
    sqlite3_close(db); 
    NSAssert(0,@"Error updating table"); 
    } 
}  

這是最簡單和最短的方式。

+0

謝謝。但我想要一個適用於任何列數的表的方法。我的代碼將適用於任何數量的列的表,但它太大,所以我想要一個小而高效的代碼 – liza 2013-03-16 09:29:40

+0

然後使用: - (void)tableInsert:(NSDictionary *)字段 char * err; ('%@','%@','%1','%','%','%','%','%','%','%','%','%','% @','%@')「,[字段valueForKey:@」field1「],[字段valueForKey:@」field2「],[字段valueForKey:@」field3「],[字段valueForKey:@」field4「]]] ; NSLog(@「%@」,sql); (sqlite3_exec(db,[sql UTF8String],NULL,NULL,&err)!= SQLITE_OK) { sqlite3_close(db); (0,@「錯誤更新表」); } } – 2013-03-16 09:40:06

+0

再次指定了列名 – liza 2013-03-16 09:53:14