IOS开发入门之iOS-FMDBDemo
白羽 2018-09-07 来源 :网络 阅读 817 评论 0

摘要:本文将带你了解IOS开发入门之iOS-FMDBDemo,希望本文对大家学IOS有所帮助。

        本文将带你了解IOS开发入门之iOS-FMDBDemo,希望本文对大家学IOS有所帮助。


【代码笔记】iOS-FMDBDemo
  
  
  
   一,效果图。

二,工程图。

三,代码。
ViewController.h


#import 
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"

@interface ViewController : UIViewController
{
    FMDatabase *db;
    NSString *database_path;
    
}
@end


 
ViewController.m


#import "ViewController.h"


#define DBNAME    @"personinfo.sqlite"
#define ID        @"id"
#define NAME      @"name"
#define AGE       @"age"
#define ADDRESS   @"address"
#define TABLENAME @"PERSONINFO"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    //初始化数据库存放目录
    [self addDocumentPath];
    //初始化界面
    [self addView];
    
    [super viewDidLoad];

}
#pragma -mark -functions
//初始化数据库存放目录
-(void)addDocumentPath
{
    //获得Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSLog(@"--documents--%@",documents);
    //添加/号,使之变成一个完整的路径
    database_path = [documents stringByAppendingPathComponent:DBNAME];
    NSLog(@"--database_path---%@",database_path);
    db = [FMDatabase databaseWithPath:database_path];
}
//初始化用户界面
-(void)addView
{
 
    //新建数据库
    UIButton *createBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    createBtn.frame=CGRectMake(60, 60, 200, 50);
    [createBtn addTarget:self action:@selector(doClickCreateButton) forControlEvents:UIControlEventTouchUpInside];
    [createBtn setTitle:@"createTable" forState:UIControlStateNormal];
    [self.view addSubview:createBtn];

    
    //插入数据库
    UIButton *insterBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    insterBtn.frame=CGRectMake(60, 130, 200, 50);
    [insterBtn addTarget:self action:@selector(doClickInsertButton) forControlEvents:UIControlEventTouchUpInside];
    [insterBtn setTitle:@"insert" forState:UIControlStateNormal];
    [self.view addSubview:insterBtn];
    
    //更新数据库
    UIButton *updateBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    updateBtn.frame=CGRectMake(60, 200, 200, 50);
    [updateBtn addTarget:self action:@selector(doClickUpdateButton) forControlEvents:UIControlEventTouchUpInside];
    [updateBtn setTitle:@"update" forState:UIControlStateNormal];
    [self.view addSubview:updateBtn];
    
    //删除数据库
    UIButton *deleteBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    deleteBtn.frame=CGRectMake(60, 270, 200, 50);
    [deleteBtn addTarget:self action:@selector(doClickDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    [deleteBtn setTitle:@"delete" forState:UIControlStateNormal];
    [self.view addSubview:deleteBtn];
    
    //查看数据库
    UIButton *selectBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    selectBtn.frame=CGRectMake(60, 340, 200, 50);
    [selectBtn addTarget:self action:@selector(doClickSelectButton) forControlEvents:UIControlEventTouchUpInside];
    [selectBtn setTitle:@"select" forState:UIControlStateNormal];
    [self.view addSubview:selectBtn];
    
    //多线程
    UIButton *multithreadBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    multithreadBtn.frame=CGRectMake(60, 410, 200, 50);
    [multithreadBtn addTarget:self action:@selector(doClickMultithreadButton) forControlEvents:UIControlEventTouchUpInside];
    [multithreadBtn setTitle:@"multithread" forState:UIControlStateNormal];
    [self.view addSubview:multithreadBtn];
    
    
}
#pragma -mark -doClickAction
//新建数据库
- (void)doClickCreateButton{
    //sql 语句
    if ([db open]) {
        
        NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];
        BOOL res = [db executeUpdate:sqlCreateTable];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"success to creating db table");
        }
        [db close];
        
    }
}

//插入数据库
-(void)doClickInsertButton{
    if ([db open]) {
        NSString *insertSql1= [NSString stringWithFormat:
                               @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                               TABLENAME, NAME, AGE, ADDRESS, @"张三", @"13", @"济南"];
        BOOL res = [db executeUpdate:insertSql1];
        if (!res) {
            NSLog(@"error when insert db table");
        } else {
            NSLog(@"success to insert db table");
        }

        
        NSString *insertSql2 = [NSString stringWithFormat:
                                @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                                TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"济南"];
        BOOL res2 = [db executeUpdate:insertSql2];
        
        if (!res2) {
             NSLog(@"error when insert db table");
        }else{
             NSLog(@"success to insert db table");
        }
        [db close];
        
    }
    
}
//修改数据库
-(void)doClickUpdateButton{
    if ([db open]) {
        NSString *updateSql = [NSString stringWithFormat:
                               @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",
                               TABLENAME,   AGE,  @"15" ,AGE,  @"13"];
        BOOL res = [db executeUpdate:updateSql];
        if (!res) {
            NSLog(@"error when update db table");
        } else {
            NSLog(@"success to update db table");
        }
        [db close];
        
    }
    
}
//删除数据库
-(void)doClickDeleteButton{
    if ([db open]) {
        
        NSString *deleteSql = [NSString stringWithFormat:
                               @"delete from %@ where %@ = '%@'",
                               TABLENAME, NAME, @"张三"];
        BOOL res = [db executeUpdate:deleteSql];
        if (!res) {
            NSLog(@"error when delete db table");
        } else {
            NSLog(@"success to delete db table");
        }
        [db close];
        
    }
    
}
//查看数据库
-(void)doClickSelectButton{
    
    if ([db open]) {
        NSString * sql = [NSString stringWithFormat:
                          @"SELECT * FROM %@",TABLENAME];
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            int Id = [rs intForColumn:ID];
            NSString * name = [rs stringForColumn:NAME];
            NSString * age = [rs stringForColumn:AGE];
            NSString * address = [rs stringForColumn:ADDRESS];
            NSLog(@"id = %d, name = %@, age = %@  address = %@", Id, name, age, address);
        }
        [db close];
    }
}
//多线程操作数据库
-(void)doClickMultithreadButton{
    
  
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    
    dispatch_async(q1, ^{
        for (int i = 0; i < 50; ++i) {
            [queue inDatabase:^(FMDatabase *db2) {
                NSString *insertSql1= [NSString stringWithFormat:
                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
                                       TABLENAME, NAME, AGE, ADDRESS];
                NSString * name = [NSString stringWithFormat:@"jack %d", i];
                NSString * age = [NSString stringWithFormat:@"%d", 10+i];
                
                
                BOOL res = [db2 executeUpdate:insertSql1, name, age,@"济南"];
                if (!res) {
                    NSLog(@"error to inster data: %@", name);
                } else {
                    NSLog(@"succ to inster data: %@", name);
                }
            }];
        }
    });
    
    dispatch_async(q2, ^{
        for (int i = 0; i < 50; ++i) {
            [queue inDatabase:^(FMDatabase *db2) {
                NSString *insertSql2= [NSString stringWithFormat:
                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
                                       TABLENAME, NAME, AGE, ADDRESS];
                
                NSString * name = [NSString stringWithFormat:@"lilei %d", i];
                NSString * age = [NSString stringWithFormat:@"%d", 10+i];
                
                BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"];
                if (!res) {
                    NSLog(@"error to inster data: %@", name);
                } else {
                    NSLog(@"succ to inster data: %@", name);
                }
            }];
        }
    });
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!

本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程