• IOS开发之数据库FMDB


    IOS开发之数据库FMDB

    1.简介

      需求作用:    

        如果需要保存大量的结构较为复杂的数据时候, 使用数据库, 例如交规考试项目

      常用的数据库:

        (1)Microsoft SQL Server 2000/2008, 中小企业使用较多

        (2)Oracle 比较复杂, 大企业使用较多

        (3)Mysql数据库, 网站使用较多

        (4)sqlite:   本地数据库, 访问数据足够快, 直接访问文件

               足够简单, 功能相对其他数据库软件不是特别齐全, 足够用了

                 足够小, 系统不超过1M, 适合在移动端上使用

    2. MesaSQlite使用

    实例:  使用数据存储存储一个班上学生的信息

          学号sid  用户名username  密码password 成绩score

          1501    zhangsan      123      100

          1502    lilei         321      90

          1503    wangwu        222      80 

    (1)创建数据库 

      打开MesaSQlite后如果选择Cancel,这就是需要你手动创建一个属于你的数据库,

      选择File-->New Database ,弹出对话框Save 填写保存的文件名和位置,

    (2)创建数据表

    (3)设计数据表(添加多个字段/列)

    (4)数据库常用操作

      增,删,改,查

     

    3.SQL结构化查询语句

    SQL Structure Query Language, 结构化查询语言, 作用就是操作数据库(创建表, 数据增删改查)

    1)创建数据表

    create table if not exists StudentInfo(sid integer, 
    username varchar(20), 
    password varchar(20),
    score varchar(20))

    (2)插入数据

    insert into StudentInfo(sid,username,password,score) values(1503,'wangwu','222','80')

    (3)查询数据

      <1>查询表格中的所有数据

    select * from StudentInfo;

      <2>查询指定的字段

        例:查询所有名字username

    select username from StudentInfo

      <3>根据指定的条件进行查询

        例:查找username为zhangsan的所有信息

    select * from StudentInfo where username='zhangsan'

      <4>根据多个条件进行查询

        例:查找username为zhangsan,并且password为123的所有信息

    select * from StudentInfo where username='zhangsan' and password='123'

      <5>查询后按需要排序

        例:根据age升序排序

          降序排列

    select * from StudentInfo order by score 

          升序排列

    select * from StudentInfo order by score desc

      <6>获取,查询数据的行数或个数

    select count(*) from StudentInfo 

    (4)修改数据

    update StudentInfo set score='100'  where username='zhangsan';

    (5)删除数据

    delete from StudentInfo where sid='1503'

    4. FMDB操作数据库

    (1)配置 (进行简单的配置即可使用)

      导入文件,

      添加二进制库 libsqlite3.dylib,

      包含头文件#import "FMDatabase.h"

        注意:说明一下iOS的安全机制————沙盒机制

    //沙盒机制
    -(void)SandBox
    {
        //IOS安全机制 - 沙盒
        //(1)每个应用内容度放在一个沙盒目录下面
        //(2)每个应用只能修改自己沙盒目录下得文件,其他应用文件无法修改
        //(3)默认文件Documents,Library,tmp
        //开发:自己创建的文件放在Documents下面
        
        //确定文件位置
        //当前应用文件夹 :NSHomeDirectory()
        NSLog(@"%@",[[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSHomeDirectory() error:nil]);
        NSLog(@"home == %@",NSHomeDirectory());
    }

    (2)使用

      实例:存储学生的信息

        a.创建数据库

    -(void)creatAndInitFMDBDatabase{
        //设置路径
        NSString *path = [NSString stringWithFormat:@"%@/Documents/stuInfo.sqlite",NSHomeDirectory()];
        
        //创建数据库(如果不存在则创建打开,如果存在则直接打开)
        _database = [[FMDatabase alloc]initWithPath:path];
        if (!_database.open) {
            NSLog(@"失败");
            return;
        }
        NSLog(@"成功");
    }

        

        b.创建数据表

    -(void)createTable{
        //executeQuery用来执行select语句
        //其他语句使用executeUpdate
        //    _database executeQuery:<#(NSString *), ...#>
        NSString *sql = @"create table if not exists StudentInfo(sid integer,username varchar(20),password varchar(20),score varchar(20))";
        BOOL b = [_database executeUpdate:sql];
        NSLog(@"creatTable = %d",b);
    }

        c.插入数据

    -(void)insertData{
        int sid = 1501;
        NSString *username = @"zhangsan";
        NSString *password = @"123";
        NSString *score = @"100";
        NSString *sql = @"insert into StudentInfo(sid,username,password,score) values(?,?,?,?)";
        
        BOOL b = [_database executeUpdate:sql,[NSString stringWithFormat:@"%d",sid],username,password,score];
        NSLog(@"insertData = %d",b);
    
    }

             d.查询数据

    -(void)queryData{
        NSString *sql = @"select * from StudentInfo";
        FMResultSet *resultSet = [_database executeQuery:sql];
        while ([resultSet next]) {
            NSLog(@"sid = %@, username = %@, password = %@, score = %@",[resultSet stringForColumn:@"sid"],[resultSet stringForColumn:@"username"],[resultSet stringForColumn:@"password"],[resultSet stringForColumn:@"score"]);
        }
    }

             e.修改和删除

          //参照数据的插入和查询

      

    5. 数据库在项目中使用-单例设计模式(交通规则考试为例)

    (1)配置 (进行简单的配置即可使用)

      导入文件,

      添加二进制库 libsqlite3.dylib,

      包含头文件#import "FMDatabase.h"

     

    (2)使用

      a.创建一个DatabaseManager的单例(继承NSObject),里面添加两个方法并实现

    //获取单例对象
    +(id)sharedInstance;
    
    //获取第一级目录
    -(NSArray *)firstLevels;

      

    #import "DatabaseManager.h"
    #import "FMDatabase.h"
    
    @interface DatabaseManager (){
        FMDatabase *_database;
    }
    
    @end
    
    @implementation DatabaseManager
    //获取单例对象
    +(id)sharedInstance{
    
        static DatabaseManager *dc = nil;
        if (dc == nil) {
            dc = [[[self class]alloc]init];
        }
        return dc;
    }
    //重写初始化的方法
    -(id)init{
        if (self = [super init]) {
            [self openDatabase];
        }
        return self;
    }
    //打开数据库
    -(void)openDatabase{
        NSString *path = [[NSBundle mainBundle]pathForResource:@"data.sqlite" ofType:nil];
        _database = [[FMDatabase alloc]initWithPath:path];
        if (!_database.open) {
            NSLog(@"打开失败");
        }
    }
    
    //获取第一级目录
    -(NSArray *)firstLevels{
        NSString *sql = @"select *from firstlevel";
        FMResultSet *resultSet = [_database executeQuery:sql];
        NSMutableArray *marr = [[NSMutableArray alloc]init];
        while ([resultSet next]) {
            
            FirstLevelModel *model = [[FirstLevelModel alloc]init];
            model.pid = [resultSet stringForColumn:@"pid"];
            model.pname = [resultSet stringForColumn:@"pname"];
            model.pcount = [resultSet stringForColumn:@"pcount"];
            
            [marr addObject:model];
        }
        return marr;
    
    }

      b.实现  

      c.创建模型model(FirstLevelModel,继承NSObject)

    #import <Foundation/Foundation.h>
    
    @interface FirstLevelModel : NSObject
    
    @property (copy,nonatomic) NSString *pid;
    @property (copy,nonatomic) NSString *pname;
    @property (copy,nonatomic) NSString *pcount;
    
    
    @end

        导入单例DatabaseManager的头文件

    #import "ViewController.h"
    
    #import "DatabaseManager.h"
    
    @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>{
        UITableView *_tableView ;
        NSMutableArray *_dataArray;
        
    }
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        //初始化_dataArray
        _dataArray = [[NSMutableArray alloc]init];
        
        //获取单例
        DatabaseManager *manager = [DatabaseManager sharedInstance];
        
        //通过遍历单例创建Model
        for (FirstLevelModel *model  in manager.firstLevels) {
            NSLog(@"name = %@",model.pname);
            //把遍历后的数据加入到_dataArray中
            [_dataArray addObject:model];
        }
        NSLog(@"%d",manager.firstLevels.count);
    
        [self creatTableView];
        
    }
    
    //创建tableView
    -(void)creatTableView{
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //返回cell的高度
        _tableView.rowHeight = 50;
        [self.view addSubview:_tableView ];
        
        //给_dataArray的数据赋值
        _dataArray = [[NSMutableArray alloc]initWithArray: [[DatabaseManager sharedInstance] firstLevels]];
        
    }
    
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        NSLog(@"%d",[[[DatabaseManager sharedInstance] firstLevels] count]);
        return [[[DatabaseManager sharedInstance] firstLevels] count];
    }
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        static NSString *inde = @"cellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:inde];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inde];
            
        }
        
        //创建model获取数据并给cell赋值
        FirstLevelModel *model = _dataArray[indexPath.row];
        cell.textLabel.text = model.pname;
        return cell;
    }
    
    //是否可以编辑
    -(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
        return YES;
    } 

     

     代码下载

  • 相关阅读:
    [SDOI2009]学校食堂Dining
    [SCOI2005]最大子矩阵
    [AHOI2009]中国象棋
    洛谷P1850 换教室(概率dp)
    洛谷[1007]梦美与线段树(线段树+概率期望)
    洛谷P3577 [POI2014]TUR-Tourism
    CF1045G AI robots(动态开点线段树)
    洛谷P4721 【模板】分治 FFT(分治FFT)
    洛谷P4726 【模板】多项式指数函数
    洛谷P4173 残缺的字符串(FFT)
  • 原文地址:https://www.cnblogs.com/BadMao/p/4393919.html
Copyright © 2020-2023  润新知