recordDict 是一个NSMutableDictionary
与表的列名相同的键。
-(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]);
}
}
此代码给出了所需的结果并适用于任何表。但我想要小代码。谁能帮我?