1. 引進(jìn) sqlite3 工具箱,在要進(jìn)行數(shù)據(jù)庫操作的類里引進(jìn)頭文件 : 因?yàn)榈谌杰浖瑯邮鞘褂?nbsp; sqlite 工具箱來操作數(shù)據(jù)庫的,只不過是簡化了操作,讓語法更接近 OC 的語法, 而不需要使用過多的 C 語法;
#import <sqlite3.h>
2. 將第三方庫加載進(jìn)工程:方法是直接將 FMDB 的源文件拖拽進(jìn)工程即可;
3. 使用第三方庫訪問數(shù)據(jù)庫
當(dāng)然了,對于高手而言,對第三方庫進(jìn)行了解后,上手是很快的,對于小白,只能一步一步走啦。
3.1 指定數(shù)據(jù)庫的存儲路徑,一般都是在沙盒根目錄下地 Documents 文件夾下,文件的后綴名是 .sqlite:如 db_students.sqlite;
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/db_student.sqlite"];
3.2 先創(chuàng)建一個 FMDatabase 的對象 *_db;
FMDatabase *_db;
使用前要先初始化
_db = [[FMDatabase alloc] initWithPath:filePath];
看它的初始化方法:在初始化方法里沒有做什么多余的操作,除了指定數(shù)據(jù)庫存儲的路徑外,沒有其他操作,0x00 是一個十六進(jìn)制的地址,代表 nil(或者說 NULL )

創(chuàng)建并打開數(shù)據(jù)庫:
[_db open];
這句代碼的作用有兩個:
1)若數(shù)據(jù)庫不存在,則創(chuàng)建并打開;
2)若數(shù)據(jù)庫已經(jīng)存在,則打開數(shù)據(jù)庫;
也許你還記得:sqlite3_open(path, &_db);
這兩句代碼的作用是一樣的,只不過前者更接近 OC 的語法,其實(shí)質(zhì)還是通過后者操作數(shù)據(jù)庫的。
3.3 創(chuàng)建表
if (![_db tableExists:@"tb_students"]){ [_db executeUpdate:@"create table tb_students (ID integer PRimary key not null unique, name text, age integer)"];} // 先調(diào)用方法,判斷表是否已經(jīng)存在,若不存在則創(chuàng)建表
整個過程則為:
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/db_student.sqlite"];_db = [[FMDatabase alloc] initWithPath:filePath];if ([_db open]){ if (![_db tableExists:@"tb_students"]) { [_db executeUpdate:@"create table tb_students (ID integer primary key not null unique, name text, age integer)"]; }}[_db close]; // 當(dāng)對數(shù)據(jù)庫的操作結(jié)束后不要忘記關(guān)閉數(shù)據(jù)庫
3.4 插入、刪除、更新、查詢表的操作
第一步:打開數(shù)據(jù)庫
第二部:數(shù)據(jù)庫操作
第三部:關(guān)閉數(shù)據(jù)庫
需要注意的是,在進(jìn)行對表的插入、刪除、更新時(shí),調(diào)用的方法是 - (BOOL)executeUpdate:(NSString*)sql, ...;
看示例:
- (void)insertTable:(ZYStudent *)stu{ if ([_db open]) { [_db executeUpdate:@"insert into tb_students (name, age) values (?, ?)", stu.name, [NSNumber numberWithInt:stu.age]]; } // 這里需要注意的是:替換 sql 語句里的 ?,不能直接使用基本類型的數(shù)據(jù),而是需要將基本類型轉(zhuǎn)換為 對象類型,符合 OC 的語法 [_db close];}
對表進(jìn)行查詢時(shí),調(diào)用的方法是: - (FMResultSet *)executeQuery:(NSString*)sql, ...;
原因大概也都知道:插入、刪除、更新操作時(shí),主要表現(xiàn)出來的變化是數(shù)據(jù)表,受影響的時(shí)表中的行(即一條或幾條記錄),而查詢操作不同,進(jìn)行查詢操作的目的就是要獲得表中的數(shù)據(jù),那么就應(yīng)該將獲得數(shù)據(jù)存儲,這樣就新引用了一個概念:結(jié)果集(ResultSet)。
在查詢操作里:可以簡單的將理解為結(jié)果集是用來接收查詢數(shù)據(jù)的,然后就可以將數(shù)據(jù)從結(jié)果集取出來,通過一定手段展示出來。
- (void)selectTable{ NSMutableArray *array = [NSMutableArray array]; if ([_db open]) { FMResultSet *rs = [_db executeQuery:@"select * from tb_students"]; while ([rs next]) { ZYStudent *stu = [[[ZYStudent alloc] init] autorelease]; stu.ID = [rs intForColumnIndex:0]; stu.name = [rs stringForColumnIndex:1]; stu.age = [rs intForColumnIndex:2]; [array addObject:stu]; } } [_db close]; NSLog(@"________%@", array);}
新聞熱點(diǎn)
疑難解答
圖片精選