IOS開發之數據庫FMDB

IOS開發之數據庫FMDB

 1.簡介

  需求做用:若是須要保存大量的結構較爲複雜的數據時候, 使用數據庫, 例如交規考試項目sql

  經常使用的數據庫:數據庫

  (1)Microsoft SQL Server 2000/2008:中小企業使用較多設計模式

  (2)Oracle:比較複雜, 大企業使用較多安全

  (3)Mysql數據庫:網站使用較多ide

  (4)sqlite:本地數據庫, 訪問數據足夠快, 直接訪問文件函數

        足夠簡單, 功能相對其餘數據庫軟件不是特別齊全, 足夠用了網站

        足夠小, 系統不超過1M, 適合在移動端上使用spa

2. MesaSQlite使用

  實例:使用數據存儲存儲一個班上學生的信息設計

   

  

  (1)建立數據庫 code

  (2)建立數據表

  (3)設計數據表(添加多個字段/列)

  (4)數據庫經常使用操做:增,刪,改,查

 

3. SQL結構化查詢語句

  SQL, Structure Query Language, 結構化查詢語言, 做用就是操做數據庫(建立表, 數據增刪改查)

簡單基本的sql語句

 

(1) 數據記錄篩選:

 

sql="select * from 數據表 where 字段名=字段值 order by 字段名 [desc]"

  

sql="select * from 數據表 where 字段名 like '%字段值%' order by 字段名 [desc]"

  

sql="select top 10 * from 數據表 where 字段名=字段值 order by 字段名 [desc]"

  

sql="select top 10 * from 數據表 order by 字段名 [desc]"

  

sql="select * from 數據表 where 字段名 in ('值1','值2','值3')"

  

sql="select * from 數據表 where 字段名 between 值1 and 值2"

 

 

(2) 更新數據記錄:

  

sql="update 數據表 set 字段名=字段值 where 條件表達式"

  

sql="update 數據表 set 字段1=值1,字段2=值2 …… 字段n=值n where 條件表達式"

  

 

(3) 刪除數據記錄:

  

sql="delete from 數據表 where 條件表達式"

  

sql="delete from 數據表" (將數據表全部記錄刪除)

  

(4) 添加數據記錄:

  

sql="insert into 數據表 (字段1,字段2,字段3 …) values (值1,值2,值3 …)"

  

sql="insert into 目標數據表 select * from 源數據表" (把源數據表的記錄添加到目標數據表)

  

(5) 數據記錄統計函數:

  

AVG(字段名) 得出一個表格欄平均值

  

COUNT(*;字段名) 對數據行數的統計或對某一欄有值的數據行數統計

  

MAX(字段名) 取得一個表格欄最大的值

  

MIN(字段名) 取得一個表格欄最小的值

  

SUM(字段名) 把數據欄的值相加

  

引用以上函數的方法:

  

sql="select sum(字段名) as 別名 from 數據表 where 條件表達式"

  

//set rs=conn.excute(sql)

  

rs("別名") 獲取統計的值,其它函數運用同上。

  

查詢去除重複值:select distinct * from table1

  

(6) 數據表的創建和刪除:

  CREATE TABLE 數據表名稱(字段1 類型1(長度),字段2 類型2(長度) …… )

 

 

  

4. FMDB操做數據庫

  (1)配置 

    <1>導入文件,

    <2>添加二進制庫 libsqlite3.dylib,

    <3>包含頭文件#import "FMDatabase.h".

  (2)使用

  

//
//  ViewController.m
//  FMDBUseDemo
//
//  Created by qf on 15-4-3.
//  Copyright (c) 2015年 lirunmin. All rights reserved.
//

#import "ViewController.h"

#import "FMDatabase.h"

@interface ViewController ()
{
    FMDatabase *_database;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //存儲學生信息
    
    //(1)建立數據庫
    [self createAndInitDatabase];
    
    //(2)建立數據表
    [self createTable];
    
    //(3)插入數據
//    [self insertData];
    
    //(4)查詢數據
    [self queryData];
    
    //(5)修改和刪除數據(參考插入數據)
    [self alterData];
//    [self deleteData];
}

-(void)alterData
{
    NSString *username = @"laosiji";
    NSString *score = @"88";
    NSString *sql = @"update StudentInfo set username = ? where score = ?";
    BOOL b = [_database executeUpdate:sql,username,score];
    NSLog(@"alter b = %d",b);
}

-(void)deleteData
{
    NSString *username = @"zhangsan";
    NSString *sql = @"delete from StudentInfo where username = ?";
    BOOL b = [_database executeUpdate:sql,username];
    NSLog(@"delete b = %d",b);
}

-(void)queryData
{
    //顯示全部人的信息
    NSString *sql = @"select * from StudentInfo";
    //FMResultSet 表示查詢後結果集
    FMResultSet *resultSet = [_database executeQuery:sql];
    
    //next方法每次獲取一條記錄,獲取不到返回nil
    while ([resultSet next]) {
        NSLog(@"sid = %@,username = %@,password = %@,score = %@",[resultSet stringForColumn:@"sid"],[resultSet stringForColumn:@"username"],[resultSet stringForColumn:@"password"],[resultSet stringForColumn:@"score"]);
    }
}

-(void)insertData
{
    int sid = 1501;
    NSString *username = @"zhangyi";
    NSString *password = @"123444";
    NSString *score = @"88";
    NSString *sql = @"insert into StudentInfo(sid,username,password,score)values(?,?,?,?)";
    //?對應的每個參數都應該是字符串,其餘類型轉化爲字符串
    BOOL b = [_database executeUpdate:sql,[NSString stringWithFormat:@"%d",sid],username,password,score];
    NSLog(@"insert b = %d",b);
}

-(void)createTable
{
    NSString *sql = @"create table if not exists "
    "StudentInfo(sid integer,"
    "username varchar(20),"
    "password varchar(20),"
    "score varchar(20));";
    
    //executeQuery用來執行select語句
    //其餘語句使用executeUpdate
    BOOL b = [_database executeUpdate:sql];
    NSLog(@"create b = %d",b);
    
}

//IOS安全機制 - 沙盒
//(1).每一個應用內容都放在一個沙盒目錄下面
//(2).每一個應用只能修改本身沙盒目錄下的文件,其餘應用文件沒法修改
//(3).默認文件夾 Documents,Library,tmp
//開發:本身建立的文件放在Documents下面

//肯定文件位置
//當前應用文件夾 NSHomeDirectory()
//

-(void)createAndInitDatabase
{
    //設置路徑
    NSString *path = [NSString stringWithFormat:@"%@/Documents/stuInfo.sqlite",NSHomeDirectory()];
    //建立數據庫(若是不存在則建立再打開,若是存在則當即打開)
    _database = [[FMDatabase alloc] initWithPath:path];
    if(!_database.open)
    {
        NSLog(@"打開失敗");
        return;
    }
    
    NSLog(@"打開成功");
}

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

@end

 

5. 數據庫在項目中使用-單例設計模式

DatabaseManager.h

//
//  DatabaseManager.h
//  TrafficRulesProject
//
//  Created by qf on 15-4-3.
//  Copyright (c) 2015年 lirunmin. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "FirstLevelModel.h"

@interface DatabaseManager : NSObject

//獲取單例對象
+(id)shareInstance;

//獲取第一級目錄
-(NSArray *)firstLevels;

@end

 

DatabaseManager.m

//
//  DatabaseManager.m
//  TrafficRulesProject
//
//  Created by qf on 15-4-3.
//  Copyright (c) 2015年 lirunmin. All rights reserved.
//

#import "DatabaseManager.h"
#import "FMDatabase.h"

@interface DatabaseManager()
{
    FMDatabase *_database;
}
@end

@implementation DatabaseManager

+(id)shareInstance
{
    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 *muarr = [[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"];
        [muarr addObject:model];
        
    }
    
    return muarr;
}

@end

 

ViewController.m

#import "ViewController.h"

#import "FMDatabase.h"

#import "DatabaseManager.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;
    
    NSMutableArray *_dataArr;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _dataArr = [[NSMutableArray alloc] init];
    
    DatabaseManager *manager = [DatabaseManager shareInstance];
    for(FirstLevelModel *model in manager.firstLevels)
    {
        [_dataArr addObject:model];
    }
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    FirstLevelModel *model = [_dataArr objectAtIndex:indexPath.row];
    cell.textLabel.text = model.pname;
    
    return cell;
    
}
相關文章
相關標籤/搜索