iPhone開發進階(9)--- 用SQLite管理數據庫

  • 博主:易飛揚
  • 原文連接 : http://www.yifeiyang.net/iphone-developer-advanced-9-management-database-using-sqlite/
  • 轉載請保留上面文字。
  • iPhone開發進階(9)--- 用SQLite管理數據庫linux

    今天咱們來看看 iPhone 中數據庫的使用方法。iPhone 中使用名爲 SQLite 的數據庫管理系統。它是一款輕型的數據庫,是遵照ACID的關聯式數據庫管理系統,它的設計目標是嵌入式的,並且目前已經在不少嵌入式產品中使用了它,它 佔用資源很是的低,在嵌入式設備中,可能只須要幾百K的內存就夠了。它可以支持Windows/Linux/Unix等等主流的操做系統,同時可以跟不少 程序語言相結合,好比Tcl、PHP、Java等,還有ODBC接口,一樣比起Mysql、PostgreSQL這兩款開源世界著名的數據庫管理系統來 講,它的處理速度比他們都快。sql

    其使用步驟大體分爲如下幾步:數據庫

    1. 建立DB文件和表格
    2. 添加必須的庫文件(FMDB for iPhone, libsqlite3.0.dylib)
    3. 經過 FMDB 的方法使用 SQLite
    建立DB文件和表格

    1
    2
    3
    4
    5
    $ sqlite3 sample.db
    sqlite> CREATE TABLE TEST(
       ...>  id INTEGER PRIMARY KEY,
       ...>  name VARCHAR(255)
       ...> );

    簡單地使用上面的語句生成數據庫文件後,用一個圖形化SQLite管理工具,好比 Lita 來管理仍是很方便的。app

    而後將文件(sample.db)添加到工程中。iphone

    添加必須的庫文件(FMDB for iPhone, libsqlite3.0.dylib)

    首先添加 Apple 提供的 sqlite 操做用程序庫 ibsqlite3.0.dylib 到工程中。svn

    位置以下
    /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS${VER}.sdk/usr/lib/libsqlite3.0.dylib


    這樣一來就能夠訪問數據庫了,可是爲了更加方便的操做數據庫,這裏使用 FMDB for iPhone。函數

    1
    svn co http://flycode.googlecode.com/svn/trunk/fmdb fmdb

    如上下載該庫,並將如下文件添加到工程文件中:工具

    FMDatabase.h
    FMDatabase.m
    FMDatabaseAdditions.h
    FMDatabaseAdditions.m
    FMResultSet.h
    FMResultSet.m
    經過 FMDB 的方法使用 SQLite

    使用 SQL 操做數據庫的代碼在程序庫的 fmdb.m 文件中大部分都列出了、只是鏈接數據庫文件的時候須要注意 — 執行的時候,參照的數據庫路徑位於 Document 目錄下,以前把剛纔的 sample.db 文件拷貝過去就行了。post

    位置以下
    /Users/xxxx/Library/Application Support/iPhone Simulator/User/Applications/xxxx/Documents/sample.db

    如下爲連接數據庫時的代碼:測試

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    BOOL success;NSError *error;NSFileManager *fm = [NSFileManager defaultManager];NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
    success = [fm fileExistsAtPath:writableDBPath];if(!success){
      NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
      success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
      if(!success){
        NSLog([error localizedDescription]);
      }
    }// 鏈接DBFMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];if ([db open]) {
      [db setShouldCacheStatements:YES];
    
      // INSERT  [db beginTransaction];
      int i = 0;
      while (i++ < 20) {
        [db executeUpdate:@"INSERT INTO TEST (name) values (?)" , [NSString stringWithFormat:@"number %d", i]];
        if ([db hadError]) {
          NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        }
      }
      [db commit];
    
      // SELECT  FMResultSet *rs = [db executeQuery:@"SELECT * FROM TEST"];
      while ([rs next]) {
        NSLog(@"%d %@", [rs intForColumn:@"id"], [rs stringForColumn:@"name"]);
      }
      [rs close];
      [db close];
    }else{
      NSLog(@"Could not open db.");
    }

    接下來再看看用 DAO 的形式來訪問數據庫的使用方法,代碼總體構造以下。

    首先建立以下格式的數據庫文件:

    1
    2
    3
    4
    5
    6
    $ sqlite3 sample.db
    sqlite> CREATE TABLE TbNote(
       ...>  id INTEGER PRIMARY KEY,
       ...>  title VARCHAR(255),
       ...>  body VARCHAR(255)
       ...> );
    建立DTO(Data Transfer Object)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    //TbNote.h#import <Foundation/Foundation.h> @interface TbNote : NSObject {
      int index;
      NSString *title;
      NSString *body;
    }
    
    @property (nonatomic, retain) NSString *title;
    @property (nonatomic, retain) NSString *body;
    
    - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody;
    - (int)getIndex;@end //TbNote.m#import "TbNote.h" @implementation TbNote @synthesize title, body;
    
    - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{
      if(self = [super init]){
        index = newIndex;
        self.title = newTitle;
        self.body = newBody;
      }
      return self;
    }
    
    - (int)getIndex{
      return index;
    }
    
    - (void)dealloc {
      [title release];
      [body release];
      [super dealloc];
    }@end
    建立DAO(Data Access Objects)

    這裏將 FMDB 的函數調用封裝爲 DAO 的方式。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    //BaseDao.h#import <Foundation/Foundation.h> @class FMDatabase;@interface BaseDao : NSObject {
      FMDatabase *db;
    }
    
    @property (nonatomic, retain) FMDatabase *db;
    
    -(NSString *)setTable:(NSString *)sql;@end //BaseDao.m#import "SqlSampleAppDelegate.h" #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "BaseDao.h" @implementation BaseDao @synthesize db;
    
    - (id)init{
      if(self = [super init]){
        // 由 AppDelegate 取得打開的數據庫    SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];
        db = [[appDelegate db] retain];
      }
      return self;
    }// 子類中實現-(NSString *)setTable:(NSString *)sql{
      return NULL;
    }
    
    - (void)dealloc {
      [db release];
      [super dealloc];
    }@end

    下面是訪問 TbNote 表格的類。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    //TbNoteDao.h#import <Foundation/Foundation.h> #import "BaseDao.h" @interface TbNoteDao : BaseDao {
    }
    
    -(NSMutableArray *)select;
    -(void)insertWithTitle:(NSString *)title Body:(NSString *)body;
    -(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body;
    -(BOOL)deleteAt:(int)index;@end //TbNoteDao.m#import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "TbNoteDao.h" #import "TbNote.h" @implementation TbNoteDao -(NSString *)setTable:(NSString *)sql{
      return [NSString stringWithFormat:sql,  @"TbNote"];
    }// SELECT-(NSMutableArray *)select{
      NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
      FMResultSet *rs = [db executeQuery:[self setTable:@"SELECT * FROM %@"]];
      while ([rs next]) {
        TbNote *tr = [[TbNote alloc]
                  initWithIndex:[rs intForColumn:@"id"]
                  Title:[rs stringForColumn:@"title"]
                  Body:[rs stringForColumn:@"body"]
                  ];
        [result addObject:tr];
        [tr release];
      }
      [rs close];
      return result;
    }// INSERT-(void)insertWithTitle:(NSString *)title Body:(NSString *)body{
      [db executeUpdate:[self setTable:@"INSERT INTO %@ (title, body) VALUES (?,?)"], title, body];
      if ([db hadError]) {
        NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
      }
    }// UPDATE-(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body{
      BOOL success = YES;
      [db executeUpdate:[self setTable:@"UPDATE %@ SET title=?, body=? WHERE id=?"], title, body, [NSNumber numberWithInt:index]];
      if ([db hadError]) {
        NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        success = NO;
      }
      return success;
    }// DELETE- (BOOL)deleteAt:(int)index{
      BOOL success = YES;
      [db executeUpdate:[self setTable:@"DELETE FROM %@ WHERE id = ?"], [NSNumber numberWithInt:index]];
      if ([db hadError]) {
        NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        success = NO;
      }
      return success;
    }
    
    - (void)dealloc {
      [super dealloc];
    }@end

    爲了確認程序正確,咱們添加一個 UITableView。使用 initWithNibName 測試 DAO。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    //NoteController.h#import <UIKit/UIKit.h> @class TbNoteDao;@interface NoteController : UIViewController <UITableViewDataSource, UITableViewDelegate>{
      UITableView *myTableView;
      TbNoteDao *tbNoteDao;
      NSMutableArray *record;
    }
    
    @property (nonatomic, retain) UITableView *myTableView;
    @property (nonatomic, retain) TbNoteDao *tbNoteDao;
    @property (nonatomic, retain) NSMutableArray *record;@end //NoteController.m#import "NoteController.h" #import "TbNoteDao.h" #import "TbNote.h" @implementation NoteController @synthesize myTableView, tbNoteDao, record;
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
      if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        tbNoteDao = [[TbNoteDao alloc] init];
        [tbNoteDao insertWithTitle:@"TEST TITLE" Body:@"TEST BODY"];// [tbNoteDao updateAt:1 Title:@"UPDATE TEST" Body:@"UPDATE BODY"];// [tbNoteDao deleteAt:1];    record = [[tbNoteDao select] retain];
      }
      return self;
    }
    
    - (void)viewDidLoad {
      [super viewDidLoad];
      myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
      myTableView.delegate = self;
      myTableView.dataSource = self;
      self.view = myTableView;
    }
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
      return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
      return [record count];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      static NSString *CellIdentifier = @"Cell";
    
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
      if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
      }
      TbNote *tr = (TbNote *)[record objectAtIndex:indexPath.row];
      cell.text = [NSString stringWithFormat:@"%i %@", [tr getIndex], tr.title];
      return cell;
    }
    
    - (void)didReceiveMemoryWarning {
      [super didReceiveMemoryWarning];
    }
    
    - (void)dealloc {
      [super dealloc];
    }@end

    最後咱們開看看鏈接DB,和添加 ViewController 的處理。這一一樣不使用 Interface Builder。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    //SqlSampleAppDelegate.h#import <UIKit/UIKit.h> @class FMDatabase;@interface SqlSampleAppDelegate : NSObject <UIApplicationDelegate> {
      UIWindow *window;
      FMDatabase *db;
    }
    
    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) FMDatabase *db;
    
    - (BOOL)initDatabase;
    - (void)closeDatabase;@end //SqlSampleAppDelegate.m#import "SqlSampleAppDelegate.h" #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "NoteController.h" @implementation SqlSampleAppDelegate @synthesize window;@synthesize db;
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
      if (![self initDatabase]){
        NSLog(@"Failed to init Database.");
      }
      NoteController *ctrl = [[NoteController alloc] initWithNibName:nil bundle:nil];
      [window addSubview:ctrl.view];
      [window makeKeyAndVisible];
    }
    
    - (BOOL)initDatabase{
      BOOL success;
      NSError *error;
      NSFileManager *fm = [NSFileManager defaultManager];
      NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];
      NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
    
      success = [fm fileExistsAtPath:writableDBPath];
      if(!success){
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
        success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        if(!success){
          NSLog([error localizedDescription]);
        }
        success = NO;
      }
      if(success){
        db = [[FMDatabase databaseWithPath:writableDBPath] retain];
        if ([db open]) {
          [db setShouldCacheStatements:YES];
        }else{
          NSLog(@"Failed to open database.");
          success = NO;
        }
      }
      return success;
    }
    
    - (void) closeDatabase{
      [db close];
    }
    
    - (void)dealloc {
      [db release];
      [window release];
      [super dealloc];
    }@end
    相關文章
    相關標籤/搜索