iOS项目开发中常用到的数据库之sqlite3并对列表进行模糊查询

来源:互联网 发布:河北网络电视台 - 百度 编辑:程序博客网 时间:2024/06/11 07:24

sqlite3 轻量级的数据库,这里就不过多的赘述,直接上代码;在这里之前呢,为了让程序结构清晰明了;这里的目录结构,一个主控制器(viewcontroller),一个工具类(ContactTool),一个model(Contact),我提供一个工具类ContactTool,并在这工具类里面写sqlite3代码

在这里了,为了保证在程序第一次进入这个类(ContactTool)的时候就能创建数据库,在ContactTool里面调用在系统的 + (void)initialize 方法中创建数据库;

这个是工具类.m文件

#import "ContactTool.h"
#import <sqlite3.h>
#import "Contact.h"

@implementation ContactTool
/*
 1.打开数据库,第一次使用这个业务类
 2.创建表格
 */
static sqlite3 *_db;
+ (void)initialize
{
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    // 拼接文件名
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"contact.sqlite"];
    
    // 打开数据库
    if (sqlite3_open(filePath.UTF8String, &_db) == SQLITE_OK) {
        NSLog(@"打开成功");
    }else{
        NSLog(@"打开失败");
    }
    
    // 创建表格
    NSString *sql = @"create table if not exists t_contact (id integer primary key autoincrement,name text,phone text);";
    char *error;
    
    sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
    
    if (error) {
        NSLog(@"创建表格失败");
    }else{
        NSLog(@"创建表格成功");

    }
    
}

+ (BOOL)execWithSql:(NSString *)sql
{
    BOOL flag;
    char *error;
    
    sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
    
    if (error) {
        flag = NO;
        NSLog(@"%s",error);
    }else{
        
        flag = YES;
        
    }
    
    return flag;
}

+ (void)saveWithContact:(Contact *)contact
{
    NSString *sql = [NSString stringWithFormat:@"insert into t_contact (name,phone) values ('%@','%@')",contact.name,contact.phone];
    BOOL flag = [self execWithSql:sql];
    if (flag) {
        NSLog(@"插入成功");
    }else{
         NSLog(@"插入失败");
    }
}

+ (NSArray *)contacts
{
  return  [self contactWithSql:@"select * from t_contact"];
}

+ (NSArray *)contactWithSql:(NSString *)sql
{
    NSMutableArray *arrM = [NSMutableArray array];
    // 准备查询,生成句柄,操作查询数据结果
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
        
        // 执行句柄
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            
            NSString *name = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
             NSString *phone = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 2)];
            
            Contact *c = [Contact contactWithName:name phone:phone];
            [arrM addObject:c];
        }
        
        
    }
    
    return arrM;
    
}

@end

这里是.h文件

#import <Foundation/Foundation.h>
@class Contact;
@interface ContactTool : NSObject

// 存

/**
 *  存储联系人
 *  contact:联系人模型
 */
+ (void)saveWithContact:(Contact *)contact;

// 取
/**
 *  获取联系人数据
 *
 *  @param sql 查询的语句
 *
 */
+ (NSArray *)contactWithSql:(NSString *)sql;

+ (NSArray *)contacts;

@end

在这里介绍一下model的.m和.h

.h文件


@interface Contact : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phone;

+ (instancetype)contactWithName:(NSString *)name phone:(NSString *)phone;


.m文件

@implementation Contact

+ (instancetype)contactWithName:(NSString *)name phone:(NSString *)phone
{
    Contact *c = [[self alloc] init];
    
    c.name = name;
    c.phone = phone;
    
    return c;
}

@end


以上两个操作是创数据库和保存数据的操作,下面还是viewcontroller调用数据库并显示的操作

 

#import "ViewController.h"
#import "Contact.h"
#import "ContactTool.h"

@interface ViewController ()<UISearchBarDelegate>
@property (nonatomic, strong) NSMutableArray *contacts;
@end

@implementation ViewController
- (NSMutableArray *)contacts
{
    if (_contacts == nil) {
        // 从数据库读取数据
        _contacts = [ContactTool contacts];
        
        if (_contacts == nil) {
            _contacts = [NSMutableArray array];
        }
    }
    return _contacts;
}

- (IBAction)insert:(id)sender {
    
    
    NSArray *nameArr = @[@"pp",@"oo",@"kk",@"xx"];
    // 生成随机数,保证每一次添加都有值
    NSString *name = [NSString stringWithFormat:@"%@%d",nameArr[arc4random_uniform(4)],arc4random_uniform(200)];

    NSString *phone = [NSString stringWithFormat:@"%d",arc4random_uniform(10000)+10000];

     // 给模型数据复制 

     Contact *c = [Contact contactWithName:name phone:phone];
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.contacts.count inSection:0];
    [self.contacts addObject:c];
    
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    // 存储到数据库里面
    [ContactTool saveWithContact:c];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    
    // 设置导航条的内容
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
    
    
}

//#warning 如果以后直接从本地数据库请求数据,就在这里写
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    // o  select * from t_contact where name like '%searchText%' or phone like '%searchText%'
    // % 在stringWithFormat中有特殊意思
    // %% == %
    // 输入一个文字,进行模糊查询,查看下名字或者电话是否包含文字
    NSString *sql = [NSString stringWithFormat:@"select * from t_contact where name like '%%%@%%' or phone like '%%%@%%';",searchText,searchText];
   _contacts = (NSMutableArray *)[ContactTool contactWithSql:sql];
    
    [self.tableView reloadData];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.contacts.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    Contact *c  = self.contacts[indexPath.row];
    cell.textLabel.text = c.name;
    cell.detailTextLabel.text = c.phone;
    return cell;
}

@end





1 1