没用FMDB封装SQLite
//内部状态判断
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];
}