FMDB操作数据库

staticFMDatabase*_db;

*****创建数据库

+ (void)createDataBaseAndCreateTableWithPath{

NSString*path =[NSHomeDirectory()stringByAppendingPathComponent:

@"Documents/database.sqlite"];

NSFileManager*manager = [NSFileManager defaultManager];

if(![managerfileExistsAtPath:path]) {

[manager createFileAtPath:pathcontents:nilattributes:nil];

}

_db= [[FMDatabase databaseWithPath:path]retain];

if([_db open]) {

NSString*createSQL = [NSStringstringWithFormat:@"create table if not exists user (id integer primary key autoincrement,textStr text not null,idStr text not null,name text,href text,sourceString text)"];

[_dbexecuteUpdate:createSQL];

}

[_db close];

}

*****插入数据

+ (void)insertDataIntoUserWithArr:(NSArray*)arr{

    for(StatusModel*model in arr) {

   NSString*insertSQL = [NSStringstringWithFormat:@"insert into user     (textStr,idStr,name,href,sourceString) values('%@','%@','%@','%@','%@')",model.text,model.idStr,model.userObj.name,model.sourceObj.href,model.sourceObj.sourceString];

   NSLog(@"%@",insertSQL);

   [_dbopen];

   [_dbexecuteUpdate:insertSQL];

  [_dbclose];

}

}

****查询数据

+ (NSMutableArray*)selectDataFromUser{

[_dbopen];

NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];

NSString *selectSQL = [NSString stringWithFormat:@"select *from user"];

FMResultSet*set = [_dbexecuteQuery:selectSQL];

while([set next]) {

StatusModel *model = [[StatusModel alloc]init];

model.text= [set stringForColumn:@"textStr"];

model.idStr= [set stringForColumn:@"idStr"];

model.userObj= [[UserModel alloc] autorelease];

model.userObj.name= [set stringForColumn:@"name"];

model.sourceObj= [[SourceModel alloc] autorelease];

model.sourceObj.href= [set stringForColumn:@"href"];

model.sourceObj.sourceString= [setstringForColumn:@"sourceString"];

[arr addObject:model];

}

[_dbclose];

returnarr;

}

*****删除数据库

+ (void)deleteDatabase{

[_db open];

NSString *dropSQL = [NSString stringWithFormat:@"delete from user"];

[_db executeUpdate:dropSQL];

[_db close];

}

你可能感兴趣的:(FMDB操作数据库)