您可以通过创建一个包含三列的表来做到这一点(使用创建表查询)。然后将这些对象从字典中插入这些列(使用插入查询)。
编辑:对于插入数据使用查询:
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 类中创建一个 sqlite 实例:
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 *idToReturn=@"";
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)
{
idToReturn=@"";
}
else
{
idToReturn =[NSString stringWithUTF8String:s];
}
[temp setObject:idToReturn forKey:@"id"];
s=(char *)sqlite3_column_text(statement, 1);
if(s==NULL)
{
idToReturn=@"";
}
else
{
idToReturn =[NSString stringWithUTF8String:s];
}
[temp setObject:idToReturn forKey:@"name"];
s=(char *)sqlite3_column_text(statement, 2);
if(s==NULL)
{
idToReturn=@"";
}
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;
}
希望它可以帮助你。