FMDB增删改查

开数据库

#pragma mark - 开数据库
- (void)openDatabase
{
    NSString *filePath = [self filepath];
    self.database = [FMDatabase databaseWithPath:filePath];
    
    if ([self.database open]) {
        //执行更新(在这里输入建表语句):
        [self.database executeUpdate:@"create table if not exists contacts(id integer primary key autoincrement , name text , mobile text)"];
    }
}

从数据库删除表格数据

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
###pragma mark - 删数据库数据
        int64_t serialId = [self.contacts[indexPath.row] serialId];
        //这里必须用@() , 包装对象;否则报错:
        /*
         *  Showing All Errors Only /Users/admin/Desktop/02-NetEase合辑/下载代码/04-文件存储/1.4 Beyond the SQLite Demo/ContactDemoFMDB跟敲代码/ContactDemo/ContactListTableViewController.m:92:57: Property 'serialId' not found on object of type 'id'
         */
        if ([self.database executeUpdate:@"delete from contacts where id = ?", @(serialId)]) {
            
            [self.contacts removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
        }
    }
}

在searchBar上查询数据库信息

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *text = searchController.searchBar.text;
    NSMutableArray *contacts = nil;
    NSString *sql = @"select * from contacts where name like ? or mobile like ?";
    if ([text length]) {
        NSString *searchText = [NSString stringWithFormat:@"%%%@%%",text];
        contacts = [NSMutableArray array];
        FMResultSet *set = [self.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];
}

读取数据库信息

#pragma mark - 读取数据库
//程序一进来就先读取一下当前数据库信息
- (void)read
{
    FMResultSet *set = [self.database executeQuery:@"select * from contacts"];
    while ([set next]) {
        Contact *contact = [[Contact alloc] init];
        //从列里获取数据:
        contact.serialId = [set longLongIntForColumn:@"id"];
        contact.name = [set stringForColumn:@"name"];
        contact.mobile = [set stringForColumn:@"mobile"];
        [self.contacts addObject:contact];
    }
    //关闭查询
    [set close];
}

愿编程让这个世界更美好

你可能感兴趣的:(FMDB增删改查)