李洪强iOS开发之-FMDB的用法

//

//  ViewController.m

//  04 - FMDB的用法

//

//  Created by 李洪强 on 2017/6/6.

//  Copyright © 2017 李洪强. All rights reserved.

//

 

#import "ViewController.h"

//导入头文件

#import "FMDB.h"

@interface ViewController ()

@property(nonatomic,strong)FMDatabase *dataBase;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    //1 创建数据库

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"student"];

    FMDatabase *dataBase = [FMDatabase databaseWithPath:path];

    self.dataBase = dataBase;

    //打开数据库

    BOOL success = [dataBase open];

    if(success){

        NSLog(@"创建数据库成功!");

        //2 创建表

         NSString *str = @"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT ,name TEXT NOT NULL,score REAL NOT NULL)";

        if([self.dataBase executeUpdate:str]){

            NSLog(@"创建表成功!");

        }else{

            NSLog(@"创建表失败!");

        }

        

    }else{

        NSLog(@"创建数据库失败!");

    }

    

    

}

//增加数据

- (IBAction)insertData:(UIButton *)sender {

    

    for(int i = 0; i < 100 ; i++){

        NSString *strName = [NSString stringWithFormat:@"ming-yuexing-%d",i];

        NSString *sqlStr = [NSString stringWithFormat:@"INSERT INTO t_student (name , score) VALUES ('%@',%.2f)",strName,arc4random_uniform(1000)/10.0];

        BOOL success = [self.dataBase executeUpdate:sqlStr];

        if(success){

            NSLog(@"添加成功");

        }else{

            NSLog(@"添加失败");

        }

    }

    

}

 

- (IBAction)selectData:(UIButton *)sender {

    NSString *sqlStr = @"SELECT * FROM t_student WHERE score > 60.0 ORDER BY score DESC";

    //执行查询语句

    FMResultSet *set = [self.dataBase executeQuery:sqlStr];

    while ([set next]) {

        NSString *name = [set stringForColumn:@"name"];

        CGFloat score = [set doubleForColumn:@"score"];

        NSLog(@"name = %@ score = %f",name,score);

    }

}

 

/*

 使用FMDBsql的好处:

 线程安全

 公共资源在A使用的时候,B不能修改

 

 

 

 

 

 

 */

 

@end

posted @ 2017-06-06 16:07  李洪强  阅读(240)  评论(0编辑  收藏  举报