一瑰步、FMDB開源第三方庫(kù)
1.非ARC模式的第三方庫(kù) -fno-objc-arc
2.系統(tǒng)依賴libsqlite3.dylib:添加方法:target-->Build Phases-->Link Binary Libraries中的"+"添加libsqlite3.dylib
FMDdatabase是一個(gè)FMDB的數(shù)據(jù)對(duì)象
FMStatement查詢到的數(shù)據(jù)集合
next FMStatement中的方法 指向下一個(gè)元素(首次不指向任何元素)
二、制定數(shù)據(jù)庫(kù)文件的路徑
1.如果路徑村子就直接讀取數(shù)據(jù)庫(kù)文件
2.如果路徑不存在就創(chuàng)建響應(yīng)路徑的數(shù)據(jù)庫(kù)文件恃鞋,同時(shí)讀取文件斋否,取沙盒的文件然后拼接到想存入的文件夾中
Documents:一般把應(yīng)用程序的數(shù)據(jù)存儲(chǔ)到此文件夾下胖齐,定期向云端備份
NSString *path=[NSString stringWithFormat:@"%@/Documents/class.db",NSHomeDirectory()];
三丛楚、FMDB第三方庫(kù)的使用
1.創(chuàng)建FMDataBase對(duì)象
FMDatabase *database=[FMDatabase databaseWithPath:path];
2.打開數(shù)據(jù)庫(kù)
如果存在數(shù)據(jù)的文件直接讀取文件箩绍,如果不存在數(shù)據(jù)庫(kù)文件創(chuàng)建并讀取數(shù)據(jù)庫(kù)文件截碴。
[database open];
3.建表
定義一個(gè)字符串是創(chuàng)建表的語句梳侨,如果表不存在就創(chuàng)建,如果表存在就不創(chuàng)建
//學(xué)號(hào)隐岛,姓名猫妙,年齡,身高
NSString * createSql = @"create table if not exists student(number integer primary key autoincrement,name varchar(20),age integer,height integer)";
BOOL createSucces = [dataBase executeUpdate:createSql];
1是創(chuàng)建成功 0是創(chuàng)建失敗
4.插入數(shù)據(jù)
//插入數(shù)據(jù)
NSString * insertStr = @"insert into student(number,name,age,height) values(1,'李四',36,169)";
BOOL? insertSucess = [dataBase executeUpdate:insertStr];
NSLog(@"%d",insertSucess);
如果插入數(shù)據(jù)模型聚凹,需要使用割坠?(問號(hào))占位(齐帚?相當(dāng)于格式控制符)代表OC中的%@
例如:
NSString * insertStr = @"insert into student(number,name,age,height) values(?,?,?,?)";
BOOL insertSucess =? ? [dataBase executeUpdate:insertStr,@"2",@"eee",@"44",@"190"];
或者 表名不確定也用格式控制符
BOOL s = [dataBase executeUpdate:[NSString stringWithFormat:@"insert into %@(number,name,age,height) values(?,?,?,?)",@"student"],@"3",@"fff",@"50",@"111"];
5.刪除數(shù)據(jù)
NSString * deleteStr = @"delete from student where height =169";
BOOL deleteSuccess = [dataBase executeUpdate:deleteStr];
NSLog(@"%d",deleteSuccess);
6.更新數(shù)據(jù)
NSString * updateStr = @"update student set name = 'wang'";
BOOL updateSucess = [dataBase executeUpdate:updateStr];
NSLog(@"%d",updateSucess);
7.查詢
NSString * selectStr = @"select * from student";
FMResultSet * selectSet = [dataBase executeQuery:selectStr];
NSLog(@"%@",selectSet);
while ([selectSet next]) {
NSString * name = [selectSet stringForColumn:@"name"];
NSLog(@"%@",name);
}
四、DQL語句的基本使用
1.通過條件來查詢對(duì)應(yīng)的數(shù)據(jù)
語句:@"select * from student where age = 44"
FMResultSet * selectSet = [dataBase executeQuery:@"select * from student where age = 44"];