ios FMDB

这篇博客详细介绍了如何在iOS应用中使用FMDB库进行数据库操作,包括创建数据模型文件、定义数据库操作类以及在ViewController中实现数据的增删操作。通过实例代码展示了如何在Objective-C中实现数据库的 CRUD 操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建继承NSObject 文件.Model
2.h中

//数据库必须得有一个主键id
@property(nonatomic,assign)NSInteger classid;

@property(nonatomic,copy)NSString *title;//标题

@property(nonatomic,copy)NSString *url;//跳转url

3.m

//找不到key值放空
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
}

4.创建继承NSObject SqlData
5…h

#import <Foundation/Foundation.h>
#import "DataModel.h"
NS_ASSUME_NONNULL_BEGIN

@interface SqlData : NSObject
//单利方法
+(instancetype)initData;
//初始化数据库
-(void)initSql;
//初始化表格
-(void)initTable;
//添加数据
-(void)addData:(id)data;
//删除数据
-(void)deleteData:(NSInteger )theid;
//查询数据
-(id)getDataArray;
//关闭数据库
-(void)closeSql;
@end

6.m

#import "SqlData.h"
#import "FMDB.h"
#import "DataModel.h"

static SqlData *sql;
static FMDatabase *db;

@implementation SqlData

+ (instancetype)initData{
    if (!sql) {
        sql = [[SqlData alloc]init];
    }
    return sql;
}

- (void)initSql{
    //创建路径
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    //拼接路径
    NSString *file = [str stringByAppendingString:@"movies.db"];
    //创建数据库
    db = [[FMDatabase alloc]initWithPath:file];
    if ([db open]) {
        NSLog(@"数据库打开");
        [self initTable];
    }else{
        NSLog(@"数据库打开失败");
    }
}

- (void)initTable{
    //初始化数据库表格的格式:create table if not exists 表名(主键id integer primary key,所有的数据类型);
    //创建表格
    [db executeUpdate:@"create table if not exists DataModel(classid integer primary key,title text,url text)"];
    //关闭数据库
    [db close];
}

- (void)addData:(DataModel *)Model{
    //添加数据库
    //添加数据的sql语句:insert into 表名 values(null,?,?);
    //先判断是否打开
    if ([db open]) {
        [db executeUpdate:[NSString stringWithFormat:@"insert into DataModel values(null,'%@','%@')",Model.title,Model.url]];
        NSLog(@"插入成功");
        NSLog(@"model ------------- %@",Model);
    }else{
        NSLog(@"打开失败");
    }
    [db close];
}

- (void)deleteData:(NSInteger)theid{
    //sql 语句: delete from 表名 where 表名的主键id = ?
    if ([db open]) {
        
        [db executeUpdate:[NSString stringWithFormat:@"delete from DataModel where classid = '%ld'",theid]];
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除数据失败");
    }
    //关闭数据库
    [db close];
}

- (NSArray *)getDataArray{
    //创建数据
    NSMutableArray *array = [NSMutableArray new];
    //集合
    FMResultSet *Set = [FMResultSet new];
    
    if ([db open]) {
        //sql 语句格式:select *from 表名
        Set = [db executeQuery:@"select * from DataModel"];
        //判断有没有东西
        while ([Set next]) {
            DataModel *dataM = [DataModel new];
            dataM.title = [Set stringForColumn:@"title"];
            dataM.url = [Set stringForColumn:@"url"];
            dataM.classid = [Set intForColumn:@"classid"];
            NSLog(@"dataM===============%@",dataM);
            [array addObject:dataM];
            NSLog(@"查询成功");
        }
    }else{
        NSLog(@"查询失败");
    }
    [db close];
    
    return array;
    
}

- (void)closeSql{
    
}

v.m中

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RightViewController *r=[RightViewController new];
    Model *MW=self.array[indexPath.row];
    r.urlString=MW;
    [self.navigationController pushViewController:r animated:YES];
}
-(void)right{
    TwoRightViewController *two=[TwoRightViewController new];
    [self.navigationController pushViewController:two animated:YES];
}

创建一个ViewController文件
.h


#import <UIKit/UIKit.h>
#import "Model.h"
NS_ASSUME_NONNULL_BEGIN

@interface RightViewController : UIViewController
@property(nonatomic,strong)Model *urlString;
@end

.m

#import "RightViewController.h"
#import "SqliteModel.h"
@interface RightViewController (){
    UIWebView *webView;
}

@end

@implementation RightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStyleDone target:self action:@selector(right)];
    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString.url]];
    [self.view addSubview: webView];
    [webView loadRequest:request];
}
-(void)right{
    //从单立中打开数据库
    [[SqliteModel initData]initSql];
    //将添加的数据给 单利
    [[SqliteModel initData]addData:self.urlString];
}

创建一个删除的页面


#import "TwoRightViewController.h"
#import "SqliteModel.h"
#import "RightViewController.h"
@interface TwoRightViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic , strong)UITableView *ojtable;
@property(nonatomic , strong)NSMutableArray *array;

@end

@implementation TwoRightViewController
-(void)viewDidAppear:(BOOL)animated{
    //打开数据库
    [[SqliteModel initData]initSql];
    self.array=[[SqliteModel initData]getDataArray];
    NSLog(@"self.array-----===========%@",self.array);
    [self.ojtable reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.ojtable];
}
- (UITableView *)ojtable{
    if (!_ojtable) {
        _ojtable = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _ojtable.delegate = self;
        _ojtable.dataSource = self;
    }
    return _ojtable;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    Model *mod = self.array[indexPath.row];
    cell.textLabel.text = mod.title;
    cell.detailTextLabel.text = mod.author_name;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RightViewController *rxq = [RightViewController new];
    Model *Mmo =self.array[indexPath.row];
    rxq.urlString = Mmo;
    [self.navigationController pushViewController:rxq animated:YES];
}
//左滑删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    //初始化model
    Model *mMD=self.array[indexPath.row];
    
    //删除id
    [[SqliteModel initData]deleteData:mMD.ID];
//    NSLog(@"%@",mMD.ID);
    self.array=[[SqliteModel initData]getDataArray];
    [tableView reloadData];
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值