iOS中 用FMDB封装一个SQLite数据库

简介: 建立一个单例: DataBaseHandle.h #import @class PersonModel;@class FMDatabase;@interface DataBaseHandle : NSObject@property(nonatomic,retain)FMD...

建立一个单例:

DataBaseHandle.h

#import <Foundation/Foundation.h>
@class PersonModel;
@class FMDatabase;
@interface DataBaseHandle : NSObject
@property(nonatomic,retain)FMDatabase *db;
//创建单例的的接口
+ (DataBaseHandle *)shareDateBaseHandle;
//创建一个Person表格
- (void)creatPersonTable;
//插入person的方法
- (void)insertPersonTable : (PersonModel *)person;
//写一个删除人的接口
- (void)deletePersonByPerssonID : (NSString *)ID;
//写一个修改人的接口
- (void)uodatePerson : (NSString *)age ByPersonID : (NSString *)ID;
//写一个查询所有人的接口
- (NSMutableArray *)selectAllPersonFromPersonTable;
@end

DataBaseHandle.m

#import "DataBaseHandle.h"
#import "FMDB.h"
#import "PersonModel.h"
@implementation DataBaseHandle
- (void)dealloc
{
    self.db = nil;
    [super dealloc];
}

创建单例的的接口:

//创建单例对象使其存在于静态区
static DataBaseHandle *handle = nil;
//创建单例的的借口
+ (DataBaseHandle *)shareDateBaseHandle{
    
    @synchronized(self){
        if (handle == nil) {
            handle = [[DataBaseHandle alloc]init];
            
            
        }
    }
    return handle;
}

写一个私有的方法,返回数据库的路径

- (NSString *)dbpath{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"db.sqlite"];
    
}

创建一个Person表格

//创建一个Person表格
- (void)creatPersonTable{
   //初始化数据库对象
    self.db = [FMDatabase databaseWithPath: [self dbpath]];
    //打开数据库
   BOOL isOpen = [self.db open];
    if (isOpen) {
        NSLog(@"打开成功");
        //创建表
     BOOL isCreat =   [self.db executeUpdate:@"create table if not exists Person(id integer primary key autoincrement,name text,gender text,age integer,salary integer)"];
        NSLog(@"%@",isCreat ? @"创建成功":@"创建失败");
        
    }else{
        NSLog(@"打开失败");
    }
}

四种方法:增、删、改、查;

//插入person的方法
- (void)insertPersonTable : (PersonModel *)person{
  BOOL isInsert =  [self.db executeUpdate:@"insert into Person(name,age)values(?,?)",person.name,person.age];
    NSLog(@"%@",isInsert ? @"插入成功":@"插入失败");
    
}

//写一个删除的接口
- (void)deletePersonByPerssonID : (NSString *)ID{
   BOOL isDelete = [self.db executeUpdate:@"delete from Person where id = ?",ID];
    NSLog(@"%@",isDelete ? @"删除成功":@"删除失败");
}

//写一个修改人的接口
- (void)uodatePerson : (NSString *)age ByPersonID : (NSString *)ID{
   BOOL isUpdate = [self.db executeUpdate:@"update Person set age = ? where id = ?",age,ID];
    NSLog(@"%@",isUpdate ? @"修改成功":@"修改失败");
}

//写一个查询所有人的接口
- (NSMutableArray *)selectAllPersonFromPersonTable{
    FMResultSet *set = [self.db executeQuery:@"select * from Person"];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    while ([set next]) {
        NSInteger ID = [set intForColumn:@"id"];
        NSString *name = [set stringForColumn:@"name"];
        NSInteger age = [set intForColumn:@"age"];
        //创建Person对象存储信息
        PersonModel *p = [[PersonModel alloc]init];
        p.ID = [NSString stringWithFormat:@"%ld",ID];
        p.name = name;
        p.age = [NSString stringWithFormat:@"%ld",age];
        //添加到数组
        [array addObject:p];
        [p release];
    }
    return array;
}

建一个model类

PersonModel.h
#import <Foundation/Foundation.h>
@interface PersonModel : NSObject
@property(nonatomic,copy)NSString *ID;
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *age;
@end

PersonModel.m
#import "PersonModel.h"

@implementation PersonModel
- (void)dealloc
{
    self.name = nil;
    self.age = nil;
    self.ID = nil;
    [super dealloc];
}
@end

===============================测试调用===============================
#import "FirstViewController.h"
#import "DataBaseHandle.h"
#import "PersonModel.h"
@interface FirstViewController ()
@property(nonatomic,retain)NSMutableArray *dataSource;//接收查询的结果
@end

@implementation FirstViewController
- (void)dealloc
{
    self.dataSource = nil;
    [super dealloc];
}

//懒加载
- (NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    
    return [[_dataSource retain]autorelease];
}
TEXT:
- (void)viewDidLoad {
    [super viewDidLoad];
    //调用并验证
    [[DataBaseHandle shareDateBaseHandle]creatPersonTable];
    NSLog(@"%@",NSHomeDirectory());
    PersonModel *p = [[PersonModel alloc]init];
    p.name = @"小韩哥";
    p.age = @"20";
    //调用插入person的方法
//    [[DataBaseHandle shareDateBaseHandle]insertPersonTable:p];
    
    //接收数据库返回的查询结果
    self.dataSource = [[DataBaseHandle shareDateBaseHandle]selectAllPersonFromPersonTable];
    
    //调用删除人的方法
    [[DataBaseHandle shareDateBaseHandle]deletePersonByPerssonID:@"9"];
    
}

配置显示:
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstcell" forIndexPath:indexPath];
    PersonModel *p = self.dataSource[indexPath.row];
    cell.textLabel.text = p.name;

    return cell;
}

布局预览:


提示:重在封装SQLite思想,不在效果,能有效调用即可!


目录
相关文章
|
5月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
484 0
|
10月前
|
SQL 数据库连接 数据库
在C++的QT框架中实现SQLite数据库的连接与操作
以上就是在C++的QT框架中实现SQLite数据库的连接与操作的基本步骤。这些步骤包括创建数据库连接、执行SQL命令、处理查询结果和关闭数据库连接。在实际使用中,你可能需要根据具体的需求来修改这些代码。
646 14
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
1243 15
|
存储 SQL 数据库
数据库知识:了解SQLite或其他移动端数据库的使用
【10月更文挑战第22天】本文介绍了SQLite在移动应用开发中的应用,包括其优势、如何在Android中集成SQLite、基本的数据库操作(增删改查)、并发访问和事务处理等。通过示例代码,帮助开发者更好地理解和使用SQLite。此外,还提到了其他移动端数据库的选择。
388 8
|
Web App开发 SQL 数据库
使用 Python 解析火狐浏览器的 SQLite3 数据库
本文介绍如何使用 Python 解析火狐浏览器的 SQLite3 数据库,包括书签、历史记录和下载记录等。通过安装 Python 和 SQLite3,定位火狐数据库文件路径,编写 Python 脚本连接数据库并执行 SQL 查询,最终输出最近访问的网站历史记录。
363 4
|
存储 关系型数据库 数据库
轻量级数据库的利器:Python 及其内置 SQLite 简介
轻量级数据库的利器:Python 及其内置 SQLite 简介
503 3
|
存储 缓存 关系型数据库
sqlite 数据库 介绍
sqlite 数据库 介绍
473 0
|
5月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
444 158
|
5月前
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。
|
5月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
1040 152