亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

iPhone開發(fā)進階(9)— 用SQLite管理數(shù)據(jù)庫

系統(tǒng) 1969 0

iPhone開發(fā)進階(9)— 用SQLite管理數(shù)據(jù)庫

?

  • 博主: 易飛揚
  • 原文鏈接?:? http://www.yifeiyang.net/iphone-developer-advanced-9-management-database-using-sqlite/
  • 轉(zhuǎn)載請保留上面文字。
  • ?

    ?

    iPhone開發(fā)進階(9)--- 用SQLite管理數(shù)據(jù)庫

    今天我們來看看 iPhone 中數(shù)據(jù)庫的使用方法。iPhone 中使用名為 SQLite 的數(shù)據(jù)庫管理系統(tǒng)。它是一款輕型的數(shù)據(jù)庫,是遵守ACID的關(guān)聯(lián)式數(shù)據(jù)庫管理系統(tǒng),它的設(shè)計目標(biāo)是嵌入式的,而且目前已經(jīng)在很多嵌入式產(chǎn)品中使用了它,它 占用資源非常的低,在嵌入式設(shè)備中,可能只需要幾百K的內(nèi)存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統(tǒng),同時能夠跟很多 程序語言相結(jié)合,比如Tcl、PHP、Java等,還有ODBC接口,同樣比起Mysql、PostgreSQL這兩款開源世界著名的數(shù)據(jù)庫管理系統(tǒng)來 講,它的處理速度比他們都快。

    其使用步驟大致分為以下幾步:

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

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

    ?

    簡單地使用上面的語句生成數(shù)據(jù)庫文件后,用一個圖形化SQLite管理工具,比如 Lita 來管理還是很方便的。

    然后將文件(sample.db)添加到工程中。

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

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

    ?

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



    這樣一來就可以訪問數(shù)據(jù)庫了,但是為了更加方便的操作數(shù)據(jù)庫,這里使用 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 操作數(shù)據(jù)庫的代碼在程序庫的 fmdb.m 文件中大部分都列出了、只是連接數(shù)據(jù)庫文件的時候需要注意 — 執(zhí)行的時候,參照的數(shù)據(jù)庫路徑位于 Document 目錄下,之前把剛才的 sample.db 文件拷貝過去就好了。

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

    ?

    以下為鏈接數(shù)據(jù)庫時的代碼:

        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]);
      }
    }
    
    // 連接DB
    FMDatabase* 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 的形式來訪問數(shù)據(jù)庫的使用方法,代碼整體構(gòu)造如下。

    ?


    iPhone開發(fā)進階(9)— 用SQLite管理數(shù)據(jù)庫
    ?首先創(chuàng)建如下格式的數(shù)據(jù)庫文件:

        $ sqlite3 sample.db
    sqlite> CREATE TABLE TbNote(
       ...>  id INTEGER PRIMARY KEY,
       ...>  title VARCHAR(255),
       ...>  body VARCHAR(255)
       ...> );
      

    ? 創(chuàng)建DTO(Data Transfer Object)

        //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
      

    ?

    創(chuàng)建DAO(Data Access Objects)

    這里將 FMDB 的函數(shù)調(diào)用封裝為 DAO 的方式。

    ?

        //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 取得打開的數(shù)據(jù)庫
        SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];
        db = [[appDelegate db] retain];
      }
      return self;
    }
    // 子類中實現(xiàn)
    -(NSString *)setTable:(NSString *)sql{
      return NULL;
    }
    
    - (void)dealloc {
      [db release];
      [super dealloc];
    }
    
    @end
      

    下面是訪問 TbNote 表格的類。

        //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
      

    為了確認(rèn)程序正確,我們添加一個 UITableView。使用 initWithNibName 測試 DAO。

        //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。

        //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
      
    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?


    ?

    ?

    ?

    ?

    iPhone開發(fā)進階(9)— 用SQLite管理數(shù)據(jù)庫


    更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

    微信掃碼或搜索:z360901061

    微信掃一掃加我為好友

    QQ號聯(lián)系: 360901061

    您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

    【本文對您有幫助就好】

    您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

    發(fā)表我的評論
    最新評論 總共0條評論
    主站蜘蛛池模板: 一区二区三 | 欧洲在线免费视频 | 四虎a级欧美在线观看 | 欧美日韩久久毛片 | 天天干天天操天天玩 | 亚洲特级aaaaaa毛片 | 日韩一区二区三区在线视频 | 国产精品第1页在线播放 | 亚洲一区二区天海翼 | 欧美高清无砖专区欧美精品 | 99精品久久| 久久久久久久网 | 欧美专区一区二区三区 | 中文字幕永久视频 | 国产成人一区二区三区视频免费蜜 | 久久精品一区二区三区四区 | 国产精品线在线精品国语 | 奇米奇米777 | 欧洲美女a视频一级毛片 | 国产欧美精品一区二区三区四区 | 中文无码久久精品 | 香蕉精品视频在线观看入口 | 亚洲成人在线网站 | 国产精品手机网站 | 一级aa免费视频毛片 | 久操香蕉 | 国产真实一区二区三区 | 天天干天天干天天干 | 伊人久久中文 | 欧美成人丝袜视频在线观看 | 日日碰日日操 | 福利综合网 | 九九99久麻豆精品视传媒 | 国产精品久久久久久一区二区 | www.四虎在线 | 欧美一区二区三区成人看不卡 | 玖玖在线播放 | 欧美一区二区三区免费观看视频 | 日韩国产欧美一区二区三区 | 国产精品视频第一区二区 | 精品国产三级v |