一燃乍、集成測試環(huán)境
1.在github中搜索FMDB https://github.com/ccgus/fmdb
2.創(chuàng)建測試工程
3.創(chuàng)建podfile 文件褥紫,安裝FMDB pod 'FMDB'
4.導(dǎo)入 #import <FMDB.h>
頭文件
二亿扁、測試用例
1.生成數(shù)據(jù)庫
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fm.db"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
2.創(chuàng)建表文件語句
3.在里面輸入
create table if not exists T_Person(
id integer not null primary key autoincrement,
age integer,
name text
);
create table if not exists T_Student(
id integer not null primary key autoincrement,
age integer,
name text,
score integer
);
4.加載sql 語句
NSString *sqlPath = [[NSBundle mainBundle] pathForResource:@"db.sql" ofType:nil];
NSString *sql = [NSString stringWithContentsOfFile:sqlPath encoding:NSUTF8StringEncoding error:nil];
5.執(zhí)行sql語句
[db open];
//執(zhí)行多條sql 語句
BOOL result = [db executeStatements:sql];
if (result) {
NSLog(@"創(chuàng)表成功");
} else {
NSLog(@"創(chuàng)表失敗");
}
[db close];
6.打開火狐瀏覽器如蚜,打開 工具
择镇,選擇 附加組件
挡逼,點(diǎn)擊左側(cè)的擴(kuò)展
,然后右側(cè)的搜索欄里面
,輸入sqlite腻豌,點(diǎn)擊 安裝
,重啟
火狐瀏覽器,點(diǎn)擊工具家坎,打開
然后點(diǎn)擊
選擇剛才創(chuàng)建好報表的數(shù)據(jù)庫
三、 插入吝梅,查詢虱疏,修改,刪除
1.插入
NSString *insertSql = @"INSERT INTO T_Person(age,name) values(?,?)";
BOOL insertResult = [db executeUpdate:insertSql withArgumentsInArray:@[@(18),@"周文剛"]];
if (insertResult) {
NSLog(@"插入成功");
} else {
NSLog(@"插入失敗");
}
2.查詢
//1.簡單查詢
NSString *selectSql = @"select id,name,age from T_Person";
FMResultSet *selectResult = [db executeQuery:selectSql];
while (selectResult.next) {
NSInteger key = [selectResult intForColumn:@"id"];
NSString *name = [selectResult stringForColumn:@"name"];
NSInteger age = [selectResult intForColumn:@"age"];
NSLog(@"key = %ld,name = %@,age = %ld",(long)key,name,(long)age);
}
執(zhí)行的結(jié)果
//2.復(fù)雜的查詢
NSMutableArray *selectArray = [NSMutableArray array];
FMResultSet *selectResult1 = [db executeQuery:selectSql];
while (selectResult1.next) {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
NSInteger count = selectResult1.columnCount;
for (int i = 0; i < count; i++) {
NSString *colName = [selectResult1 columnNameForIndex:i];
id colValue = [selectResult1 objectForColumn:colName];
dic[colName] = colValue;
}
[selectArray addObject:dic];
}
NSLog(@"%@",selectArray);
運(yùn)行結(jié)果截圖
3.更新
NSString *updateSql = @"update T_Person set name = ?, age = ? where id = ?";
BOOL resultupdate = [db executeUpdate:updateSql withArgumentsInArray:@[@"小明",@17,@1]];
if (resultupdate) {
NSLog(@"更新成功");
} else {
NSLog(@"更新失敗");
}
4.刪除
NSString *deleteSql = @"delete from T_Person where id = 2";
BOOL resultDelete = [db executeUpdate:deleteSql];
if (resultDelete) {
NSLog(@"刪除成功");
} else {
NSLog(@"刪除失敗");
}
運(yùn)行結(jié)果