封装第三方库FMDB(SQLite)
没用FMDB封装SQLite
文章图片
打开和关闭数据库
文章图片
执行sql语句
文章图片
//内部状态判断
1._db是否可用
2.sql语句是否是合法状态
//解析参数
va_list args;
va_start(args,sql);
/*获取有多少个参数需要绑定*/
NSArray *bindArgs = [self parseArguments:args];
va_end(args);
//绑定参数
通过bindObject 这个自定义的方法,对传过来的参数进行绑定
FMDB封装的SQLite

文章图片
https://github.com/ccgus/fmdb demo FMDB要求我们每一个传进去的参数都是一个objc对象
- 返回的路径操作
- (NSString *)filepath
{
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
return[documents stringByAppendingPathComponent:@"contacts.db"];
}
- 打开数据库操作
- (void)openDatabase
{
NSString *filepath = [self filepath];
_database = [FMDatabase databaseWithPath:filepath];
if ([_database open])
{
if (![_database executeUpdate:@"create table if not exists contacts(id integer primary key autoincrement,name text,mobile text)"])
{
NSLog(@"open database failed");
}
}
else
{
NSLog(@"open database failed");
}
}
- 关闭数据库操作
- (void)dealloc
{
[_database close];
}
- 读取数据库操作
- (void)read
{
FMResultSet *set=[_database executeQuery:@"select *from contacts"];
while ([set next]) {
Contact *contact=[[Contact alloc]init];
contact.serialId=[set unsignedLongLongIntForColumn:@"id"];
contact.name=[set stringForColumn:@"name"];
contact.mobile=[set stringForColumn:@"mobile"];
[self.contacts addObject:contact];
}
[set close];
}
- 从数据库删除数据操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSInteger index = [indexPath row];
int64_t serialId = [self.contacts[index] serialId];
if ([_database executeUpdate:@"delete from contacts where id = ?",@(serialId)])
{
[self.contacts removeObjectAtIndex:index];
[self.tableView reloadData];
}
}
}
从数据库搜索操作
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *text = searchController.searchBar.text;
NSMutableArray *contacts = nil;
if ([text length])
{
NSString *searchText = [NSString stringWithFormat:@"%%%@%%",text];
contacts = [NSMutableArray array];
NSString *sql = @"select * from contacts where name like ? or mobile like ?";
FMResultSet *set = [_database executeQuery:sql,searchText,searchText];
while ([set next])
{
Contact *contact =[[Contact alloc] init];
contact.serialId = [set longLongIntForColumn:@"id"];
contact.name = [set stringForColumn:@"name"];
contact.mobile = [set stringForColumn:@"mobile"];
[contacts addObject:contact];
}
[set close];
}self.filteredContacts = contacts;
[self.tableView reloadData];
}
推荐阅读
- Docker应用:容器间通信与Mariadb数据库主从复制
- android第三方框架(五)ButterKnife
- 太平之莲
- 2020-04-07vue中Axios的封装和API接口的管理
- 基于|基于 antd 风格的 element-table + pagination 的二次封装
- python自定义封装带颜色的logging模块
- thinkphp|thinkphp 3.2 如何调用第三方类库
- 我正在参加安特思库共读一本书干法。
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- 现役联盟前十怎么排(詹姆斯榜首无悬念!杜兰特库里位置不确定!)