FMDB的用法相對簡單逊彭,主要有幾個步驟:初始化并打開數(shù)據(jù)庫,創(chuàng)建表格匪燕,執(zhí)行查詢或更新語句蕾羊,具體如下:
- 1,初始化并打開數(shù)據(jù)庫
//1帽驯,初始化并打開數(shù)據(jù)庫
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"company.sqlite"];
NSLog(@"%@",path);
_database = [[FMDatabase alloc] initWithPath:path];
[_database open];
- 2龟再, 創(chuàng)建表格
//2, 創(chuàng)表
[_database executeUpdate:@"CREATE TABLE IF NOT EXISTS t_company (id interger PRIMARY KEY, name text NOT NULL)"];
- 3, 執(zhí)行更新語句:包括增加,刪除等除查詢之外的所有其他操作
//3.1,增加數(shù)據(jù)
//方式一:無格式型
[_database executeUpdate:@"insert into t_company (name) values ('zhangdanfengzhangdanfeng')"];
//方式二:有格式
for (int i=0; i<100;i++) {
NSString *name = [NSString stringWithFormat:@"jiji-%d", arc4random_uniform(500)];
[_database executeUpdateWithFormat:@"insert into t_company (name) values (%@)",name];
}
//3.2,刪除數(shù)據(jù)(刪除名字中有問號的所有值)
[_database executeUpdate:@"delete from t_company where name like '%?%'"];
- 4, 執(zhí)行查詢語句
//4尼变,查詢數(shù)據(jù)利凑,%是通配符,表示一個或者一個以上的任意值
FMResultSet *set = [_database executeQuery:@"select * from t_company where name like '%?%'"];
while (set.next) {
NSString *name = [set stringForColumn:@"name"];
NSLog(@"%@",name);
}