iOS 使用FMDB進行數據庫操作

iOS 使用FMDB進行數據庫操作

1、首先要先導入第三方類庫FMdatabase。

2、獲得存放數據庫文件的沙盒地址。


+(NSString *)databaseFilePath
{
 
NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [filePath objectAtIndex:0];
NSLog(@"%@",filePath);
NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"db.sqlite"];
return dbFilePath; 
 
}



3、創建數據庫的操作

+(void)creatDatabase
{
    db = [[FMDatabasedatabaseWithPath:[selfdatabaseFilePath]] retain];
}


4、創建表

+(void)creatTable
{
//先判斷數據庫是否存在,如果不存在,創建數據庫
if (!db) {
[selfcreatDatabase];
}
//判斷數據庫是否已經打開,如果沒有打開,提示失敗 
if (![db open]) {
NSLog(@"數據庫打開失敗");
return;
}

//爲數據庫設置緩存,提高查詢效率 
[dbsetShouldCacheStatements:YES];
 
//判斷數據庫中是否已經存在這個表,如果不存在則創建該表
if(![dbtableExists:@"people"])
{
[db executeUpdate:@"CREATE TABLES people(people_id INTEGER PRIMARY KEY AUTOINCREAMENT, name TEXT, age INTEGER) "];
 
 
NSLog(@"創建完成");
}
 
}


5、增加表數據

+(void)insertPeople:(People *)aPeople
{
if (!db) {
[selfcreatDatabase];
}
 
if (![db open]) {
NSLog(@"數據庫打開失敗");
return;
}
 
[dbsetShouldCacheStatements:YES];
 
if(![dbtableExists:@"people"])
{
[selfcreatTable];
}
//以上操作與創建表是做的判斷邏輯相同
//現在表中查詢有沒有相同的元素,如果有,做修改操作 
FMResultSet *rs = [dbexecuteQuery:@"select * from people where people_id = ?",[NSStringstringWithFormat:@"%d",aPeople.peopleID]];
if([rs next]) 
{
NSLog(@"dddddslsdkien");
[dbexecuteUpdate:@"update people set name = ?, age = ? where people_id = 1",aPeople.name,[NSStringstringWithFormat:@"%d",aPeople.age]];
}
//向數據庫中插入一條數據 
else{
[dbexecuteUpdate:@"INSERT INTO people (name, age) VALUES (?,?)",aPeople.name,[NSStringstringWithFormat:@"%d",aPeople.age]];
} 
 
}



6、刪除數據

+(void)deletePeopleByID:(int)ID
{
if (!db) {
[selfcreatDatabase];
}
 
if (![db open]) {
NSLog(@"數據庫打開失敗");
return;
}
 
[dbsetShouldCacheStatements:YES];
 
//判斷表中是否有指定的數據, 如果沒有則無刪除的必要,直接return
if(![dbtableExists:@"people"])
{
return;
}
//刪除操作 
[db executeUpdate:@"delete from people where people_id = ?", [NSStringstringWithFormat:@"%d",ID]];
 
[db close];
}



7、修改操作與增加操作的步驟一致

8、查詢

+(NSArray *)getAllPeople
{
 
if (!db) {
[selfcreatDatabase];
}
 
if (![db open]) {
NSLog(@"數據庫打開失敗");
return nil;
}
 
[dbsetShouldCacheStatements:YES];
 
if(![dbtableExists:@"people"])
{
return nil;
}

//定義一個可變數組,用來存放查詢的結果,返回給調用者 
NSMutableArray *peopleArray = [[NSMutableArrayalloc] initWithArray:0];
//定義一個結果集,存放查詢的數據
FMResultSet *rs = [dbexecuteQuery:@"select * from people"];
//判斷結果集中是否有數據,如果有則取出數據
while ([rs next]) {
People *aPeople = [[People alloc] init];
 
aPeople.peopleID = [rs intForColumn:@"people_id"];
aPeople.name = [rs stringForColumn:@"name"];
aPeople.age = [rs intForColumn:@"age"];
//將查詢到的數據放入數組中。 
[peopleArray addObject:aPeople];
}
return [peopleArray autorelease];
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章