【代码笔记】iOS-FMDBDemo

一,效果图。

二,工程图。

三,代码。

ViewController.h

#import <UIKit/UIKit.h>
#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

时间: 2024-12-27 14:53:02

【代码笔记】iOS-FMDBDemo的相关文章

WWDC 2014 Session笔记 - iOS界面开发的大一统

本文是我的 WWDC 2014 笔记 中的一篇,涉及的 Session 有 What's New in Cocoa Touch Building Adaptive Apps with UIKit What's New in Interface Builder View Controller Advancements in iOS 8 A Look Inside Presentation Controllers iOS 8 和 OS X 10.10 中一个被强调了多次的主题就是大一统,Apple

iOS开发笔记--iOS开发规范

iOS开发规范 原文地址:http://blog.csdn.net/pjk1129/article/details/45146955 引子 在看下面之前,大家自我检测一下自己写的代码是否规范,代码风格是否过于迥异阅读困难?可以相互阅读同伴的代码,是否存在阅读障碍? 若存在晦涩难懂的,理解成本增大的代码,说明你的团队需要自省了. 下面总结一下OC编程中的一些代码规范(苹果官方推荐的).以OC为示例,但不局限于OC,也可以被当作别的编程语言的开发规范约定(仅需要把OC特有的东西按照你所使用的语言的惯

多线程二(GCD)代码笔记

// // TWFXViewController.h // Demo_GCD // // Created by Lion User on 12-12-11. // Copyright (c) 2012年 Lion User. All rights reserved. // #import <UIKit/UIKit.h> @interface TWFXViewController : UIViewController @property (retain, nonatomic) IBOutlet

JfinalUIB 代码笔记 (4)--- 高仿ibatis(mybatis)实现sql的集中管理

实现sql的集中管理,简单的把一些固定长度的sql移植进xml很简单,这没有什么好多说的,关键问题是我们平时处理的sql,有大量是动态长度的,比如说最常见的就是多条件的分页查询,往往我们会在代码中写大量的if else,想把这些移植进xml就比较困难了,完全仿制ibatis来做xml标签工作量太大,最省事的处理方法就是能不能直接把Java代码的逻辑处理方式移植进xml,然后对逻辑代码进行解析,绕开那一大堆的xml标签定义,下面就是jfinaluib中的处理方式: 1.0 暂时还是用的拼接,没有预

汇编代码笔记 动态更新中

汇编考完了,悲剧的93分,,,,,以后的汇编就用的少了,凡是用到都来这里做点代码笔记: 一.错误总结: 1.程序最后END +起始标号,否则U的时候需要自己手动找起始位置而且有可能程序翻译指令错误 2.对内存单元进行操作的时候,注意类型的指定,比如inc [si]必然是错的因为没有类型,还有处理数据计数器si注意加一 3.凡是用到[si]这种形式的,都注意声明BYTEPTR,WORD PTR 4.同3的错误,如果声明了COUNTDB 3,那么mov cx,count就是不对的,因为类型不匹配 5

《linux 内核完全剖析》 vsprintf.c 代码笔记

Flex1 到 Flex3 使用的都是 Halo组件,这里将介绍Halo 组件中的List 和 DataGrid .其中 DataGrid 是显示多列数据中最常用的方式.但是在Spark中还有没对应DataGrid的组件. 先写个"食物"的模型 Dinner.as . package model { [Bindable] public class Dinner { public var name:String; public var food:String; public var du

设计模式与代码重构——ios篇

有一阵子没写技术分享文了,最近每个月写一篇个人空间日记.主要是觉得自己技术比较一般写不出有质量的东西,误人子弟.互联网信息膨胀,让我们获取信息更加便捷,然而获取个人所需的正确信息,却需要每个人具备更强的搜索能力.搜索能力作为代码,就需要更优的算法.算法就像是程序的CPU,决定着程序的运行效率. 与其说电脑改变了世界,不如说是电脑改变了人类改变世界的效率.电脑其实是根据人脑设计的,而程序思想和人的思想相通,所以一个程序员在学会一门语言后,学习第二门语言会来的容易很多,因为编程思想是相通的.我认为,

iOS开发笔记--iOS动画总结

摘要 本文主要介绍核iOS中的动画:核心动画Core Animation, UIView动画, Block动画, UIImageView的帧动画. 核心动画Core Animation UIView动画 Block动画 UIImageView的帧动画 iOS中的动画 Core Animation CAAnimation: CAPropertyAnimation CAKeyframeAnimation CATransition UIView动画 Block动画 UIImageView的帧动画 UI

iOS开发笔记--iOS中的多线程

摘要 本文主要介绍iOS开发中的三种多线程技术:NSThread, NSOperation/NSOperationQueue, GCD.以及在多线程编程中的注意点和小技巧. 多线程 NSThread NSOperation/NSOperationQueue GCD 目录[-] iOS中的多线程 iOS的三种多线程技术特点: GCD基本思想 队列: 操作: 不同队列中嵌套同步操作dispatch_sync的结果: 同步操作dispatch_sync的应用场景: GCD优点: GCD队列: NSOp

资源 | 数十种TensorFlow实现案例汇集:代码+笔记

选自 Github 机器之心编译 参与:吴攀.李亚洲 这是使用 TensorFlow 实现流行的机器学习算法的教程汇集.本汇集的目标是让读者可以轻松通过案例深入 TensorFlow. 这些案例适合那些想要清晰简明的 TensorFlow 实现案例的初学者.本教程还包含了笔记和带有注解的代码. 项目地址:https://github.com/aymericdamien/TensorFlow-Examples 教程索引 0 - 先决条件 机器学习入门: 笔记:https://github.com/