数据库 第三方库FMDB 使用

---恢复内容开始---

FMDB 为第三方库,可以在github上下载地址

https://github.com/ccgus/fmdb

使用fmdb的时候先在xcode上添加sqline3 库

在jithub上下载的包后将fmdb文件夹添加xode上中去

新建项目倒入头文件FMDB.hhttps://github.com/ccgus/fmdb即可

 项目实践

 

---恢复内容结束---

FMDB 为第三方库,可以在github上下载地址

https://github.com/ccgus/fmdb

使用fmdb的时候先在xcode上添加sqline3 库

在jithub上下载的包后将fmdb文件夹添加xode上中去

新建项目倒入头文件FMDB.hhttps://github.com/ccgus/fmdb即可

 项目实践

未使用 fmdb 第三方库的使用

#import "HMViewController.h"
#import <sqlite3.h>
#import "HMShop.h"

@interface HMViewController () <UITableViewDataSource, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *priceField;
/** 数据库对象实例 */
@property (nonatomic, assign) sqlite3 *db;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)insert;
@property (nonatomic, strong) NSMutableArray *shops;
@end

@implementation HMViewController

- (NSMutableArray *)shops
{
    if (!_shops) {
        self.shops = [[NSMutableArray alloc] init];
    }
    return _shops;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 增加搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.frame = CGRectMake(0, 0, 320, 44);
    searchBar.delegate = self;
    self.tableView.tableHeaderView = searchBar;
    
    // 初始化数据库
    [self setupDb];
    
    // 查询数据
    [self setupData];
    
    // 关闭数据库
    //    sqlite3_close();
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.shops removeAllObjects];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT name,price FROM t_shop WHERE name LIKE '%%%@%%' OR  price LIKE '%%%@%%' ;", searchText, searchText];
    // stmt是用来取出查询结果的
    sqlite3_stmt *stmt = NULL;
    // 准备
    int status = sqlite3_prepare_v2(self.db, sql.UTF8String, -1, &stmt, NULL);
    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
        while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
            const char *name = (const char *)sqlite3_column_text(stmt, 0);
            const char *price = (const char *)sqlite3_column_text(stmt, 1);
            
            HMShop *shop = [[HMShop alloc] init];
            shop.name = [NSString stringWithUTF8String:name];
            shop.price = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
        }
    }
    
    [self.tableView reloadData];
}

/**
 查询数据
 */
- (void)setupData
{
    const char *sql = "SELECT name,price FROM t_shop;";
    // stmt是用来取出查询结果的
    sqlite3_stmt *stmt = NULL;
    // 准备
    int status = sqlite3_prepare_v2(self.db, sql, -1, &stmt, NULL);
    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
        while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
            const char *name = (const char *)sqlite3_column_text(stmt, 0);
            const char *price = (const char *)sqlite3_column_text(stmt, 1);
            
            HMShop *shop = [[HMShop alloc] init];
            shop.name = [NSString stringWithUTF8String:name];
            shop.price = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
        }
    }
}

/**
 初始化数据库
 */
- (void)setupDb
{
    // 打开数据库(连接数据库)
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
    // 如果数据库文件不存在, 系统会自动创建文件自动初始化数据库
    int status = sqlite3_open(filename.UTF8String, &_db);
    if (status == SQLITE_OK) { // 打开成功
        NSLog(@"打开数据库成功");
        
        // 创表
        const char *sql = "CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);";
        char *errmsg = NULL;
        sqlite3_exec(self.db, sql, NULL, NULL, &errmsg);
        if (errmsg) {
            NSLog(@"创表失败--%s", errmsg);
        }
    } else { // 打开失败
        NSLog(@"打开数据库失败");
    }
}

- (IBAction)insert {
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_shop(name, price) VALUES ('%@', %f);", self.nameField.text, self.priceField.text.doubleValue];
    sqlite3_exec(self.db, sql.UTF8String, NULL, NULL, NULL);
    
    // 刷新表格
    HMShop *shop = [[HMShop alloc] init];
    shop.name = self.nameField.text;
    shop.price = self.priceField.text;
    [self.shops addObject:shop];
    [self.tableView reloadData];
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shops.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"shop";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        cell.backgroundColor = [UIColor grayColor];
    }
    
    HMShop *shop = self.shops[indexPath.row];
    cell.textLabel.text = shop.name;
    cell.detailTextLabel.text = shop.price;
    
    return cell;
}
@end

使用FMDB第三方库

HMShopTool.h 未做操作
HMShopTool.m 
#import "HMShopTool.h"
#import "FMDB.h"
#import "HMShop.h"

@implementation HMShopTool

static FMDatabase *_db;

+ (void)initialize
{
    // 1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    
    // 2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);"];
}

+ (void)addShop:(HMShop *)shop
{
    [_db executeUpdateWithFormat:@"INSERT INTO t_shop(name, price) VALUES (%@, %f);", shop.name, shop.price];
}

+ (NSArray *)shops
{// 得到结果集
    FMResultSet *set = [_db executeQuery:@"SELECT * FROM t_shop;"];
    
    // 不断往下取数据
    NSMutableArray *shops = [NSMutableArray array];
    while (set.next) {
        // 获得当前所指向的数据
        HMShop *shop = [[HMShop alloc] init];
        shop.name = [set stringForColumn:@"name"];
        shop.price = [set doubleForColumn:@"price"];
        [shops addObject:shop];
    }
    return shops;
}
@end

 

创建模型

HMShop.h
HMShop.m未做操作
#import <Foundation/Foundation.h>

@interface HMShop : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) double  price;
@end

//在viewcontroller中使用fmdb的工具,只需导入把fmdb中去的HMShopTool.h即可,用法

#import "HMViewController.h"
//#import "FMDB.h"
#import "HMShop.h"
#import "HMShopTool.h"

@interface HMViewController ()
//@property (nonatomic, strong) FMDatabase *db;
@end

@implementation HMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 1.打开数据库
//    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
//    self.db = [FMDatabase databaseWithPath:path];
//    [self.db open];
//    
//    // 2.创表
//    [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);"];
    // executeQuery:查询数据
//    [self.db executeQuery:<#(NSString *), ...#>];
    
    // executeUpdate:除查询数据以外的其他操作
//    [self.db executeUpdate:<#(NSString *), ...#>];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    //取出模型
    NSArray *shops = [HMShopTool shops];

    //转模型
    for (HMShop *shop in shops) {
        NSLog(@"%@ %f", shop.name, shop.price);
    }
    
}
@end

 

posted @ 2015-10-14 17:21  Lee_M  阅读(234)  评论(0编辑  收藏  举报