iOS中 用FMDB封裝一個SQLite數據庫

jopen 10年前發布 | 1K 次閱讀 Objective-C IOS

建立一個單例:

DataBaseHandle.h

#import <Foundation/Foundation.h>
@class PersonModel;
@class FMDatabase;
@interface DataBaseHandle : NSObject
@property(nonatomic,retain)FMDatabase *db;
//創建單例的的接口

  • (DataBaseHandle *)shareDateBaseHandle; //創建一個Person表格
  • (void)creatPersonTable; //插入person的方法
  • (void)insertPersonTable : (PersonModel *)person; //寫一個刪除人的接口
  • (void)deletePersonByPerssonID : (NSString *)ID; //寫一個修改人的接口
  • (void)uodatePerson : (NSString )age ByPersonID : (NSString )ID; //寫一個查詢所有人的接口
  • (NSMutableArray *)selectAllPersonFromPersonTable; @end</pre>

    DataBaseHandle.m

    #import "DataBaseHandle.h"
    #import "FMDB.h"
    #import "PersonModel.h"
    @implementation DataBaseHandle
  • (void)dealloc { self.db = nil; [super dealloc]; }</pre>


    創建單例的的接口:

    //創建單例對象使其存在于靜態區
    static DataBaseHandle *handle = nil;
    //創建單例的的借口
  • (DataBaseHandle *)shareDateBaseHandle{

    @synchronized(self){

      if (handle == nil) {
          handle = [[DataBaseHandle alloc]init];
    }
}
return handle;

}</pre>

寫一個私有的方法,返回數據庫的路徑

- (NSString *)dbpath{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"db.sqlite"];

}</pre>

創建一個Person表格

//創建一個Person表格

  • (void)creatPersonTable{ //初始化數據庫對象 self.db = [FMDatabase databaseWithPath: [self dbpath]]; //打開數據庫 BOOL isOpen = [self.db open]; if (isOpen) {

      NSLog(@"打開成功");
      //創建表
    

    BOOL isCreat = [self.db executeUpdate:@"create table if not exists Person(id integer primary key autoincrement,name text,gender text,age integer,salary integer)"];

      NSLog(@"%@",isCreat ? @"創建成功":@"創建失敗");
    
    

    }else{

      NSLog(@"打開失敗");
    

    } }</pre>
    四種方法:增、刪、改、查;

    //插入person的方法

  • (void)insertPersonTable : (PersonModel *)person{ BOOL isInsert = [self.db executeUpdate:@"insert into Person(name,age)values(?,?)",person.name,person.age]; NSLog(@"%@",isInsert ? @"插入成功":@"插入失敗");

}

//寫一個刪除的接口

  • (void)deletePersonByPerssonID : (NSString *)ID{ BOOL isDelete = [self.db executeUpdate:@"delete from Person where id = ?",ID]; NSLog(@"%@",isDelete ? @"刪除成功":@"刪除失敗"); }

//寫一個修改人的接口

  • (void)uodatePerson : (NSString )age ByPersonID : (NSString )ID{ BOOL isUpdate = [self.db executeUpdate:@"update Person set age = ? where id = ?",age,ID]; NSLog(@"%@",isUpdate ? @"修改成功":@"修改失敗"); }

//寫一個查詢所有人的接口

  • (NSMutableArray )selectAllPersonFromPersonTable{ FMResultSet set = [self.db executeQuery:@"select from Person"]; NSMutableArray array = [NSMutableArray arrayWithCapacity:0]; while ([set next]) {
      NSInteger ID = [set intForColumn:@"id"];
      NSString *name = [set stringForColumn:@"name"];
      NSInteger age = [set intForColumn:@"age"];
      //創建Person對象存儲信息
      PersonModel *p = [[PersonModel alloc]init];
      p.ID = [NSString stringWithFormat:@"%ld",ID];
      p.name = name;
      p.age = [NSString stringWithFormat:@"%ld",age];
      //添加到數組
      [array addObject:p];
      [p release];
    
    } return array; }</pre>
    建一個model類


    PersonModel.h
    #import <Foundation/Foundation.h>
    @interface PersonModel : NSObject
    @property(nonatomic,copy)NSString ID;
    @property(nonatomic,copy)NSString name;
    @property(nonatomic,copy)NSString *age;
    @end

PersonModel.m

import "PersonModel.h"

@implementation PersonModel

  • (void)dealloc { self.name = nil; self.age = nil; self.ID = nil; [super dealloc]; } @end</pre>
    ===============================測試調用===============================
    #import "FirstViewController.h"
    #import "DataBaseHandle.h"
    #import "PersonModel.h"
    @interface FirstViewController ()
    @property(nonatomic,retain)NSMutableArray *dataSource;//接收查詢的結果
    @end

@implementation FirstViewController

  • (void)dealloc { self.dataSource = nil; [super dealloc]; }</pre>
    //懶加載
  • (NSMutableArray *)dataSource{ if (_dataSource == nil) {

      self.dataSource = [NSMutableArray arrayWithCapacity:0];
    

    }

    return [[_dataSource retain]autorelease]; }</pre> TEXT:

    - (void)viewDidLoad {
      [super viewDidLoad];
      //調用并驗證
      [[DataBaseHandle shareDateBaseHandle]creatPersonTable];
      NSLog(@"%@",NSHomeDirectory());
      PersonModel *p = [[PersonModel alloc]init];
      p.name = @"小韓哥";
      p.age = @"20";
      //調用插入person的方法
    //    [[DataBaseHandle shareDateBaseHandle]insertPersonTable:p];

    //接收數據庫返回的查詢結果 self.dataSource = [[DataBaseHandle shareDateBaseHandle]selectAllPersonFromPersonTable];

    //調用刪除人的方法 [[DataBaseHandle shareDateBaseHandle]deletePersonByPerssonID:@"9"];

}</pre>
配置顯示:

#pragma mark - Table view data source

  • (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections. return 1; }

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section. return self.dataSource.count; }

  • (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath )indexPath { UITableViewCell cell = [tableView dequeueReusableCellWithIdentifier:@"firstcell" forIndexPath:indexPath]; PersonModel *p = self.dataSource[indexPath.row]; cell.textLabel.text = p.name;

    return cell; }</pre>
    來自:http://blog.csdn.net/qq_31810357/article/details/49181453

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!