自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

深度解析iPhone中數(shù)據(jù)庫使用方法

移動開發(fā) iOS
SQLite 能夠支持Windows/Linux/Unix等等主流的操作系統(tǒng),同時能夠跟很多程序語言相結(jié)合,比如 Tcl、PHP、Java 等,還有 ODBC 接口,同樣比起 Mysql、PostgreSQL 這兩款開源世界著名的數(shù)據(jù)庫管理系統(tǒng)來講,它的處理速度比他們都快。

iPhone數(shù)據(jù)庫使用方法是本文介紹的內(nèi)容,iPhone 中使用名為 SQLite 數(shù)據(jù)庫管理系統(tǒng)。它是一款輕型的數(shù)據(jù)庫,是遵守ACID的關聯(lián)式數(shù)據(jù)庫管理系統(tǒng),它的設計目標是嵌入式的,而且目前已經(jīng)在很多嵌入式產(chǎn)品中使用了它,它占用資源非常的低,在嵌入式設備中,可能只需要幾百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文件和表格

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

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

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

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

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

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

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

  1. FMDatabase.h  
  2. FMDatabase.m  
  3. FMDatabaseAdditions.h  
  4. FMDatabaseAdditions.m  
  5. FMResultSet.h  
  6. FMResultSet.m 

通過 FMDB 的方法使用 SQLite

使用 SQL 操作數(shù)據(jù)庫的代碼在程序庫的 fmdb.m 文件中大部分都列出了、只是連接數(shù)據(jù)庫文件的時候需要注意 — 執(zhí)行的時候,參照的數(shù)據(jù)庫路徑位于 Document 目錄下,之前把剛才的 sample.db 文件拷貝過去就好了。

位置如下

  1. /Users/xxxx/Library/Application Support/iPhone Simulator/User/Applications/xxxx/Documents/sample.db 

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

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

接下來再看看用 DAO 的形式來訪問數(shù)據(jù)庫的使用方法,代碼整體構(gòu)造如下。

iPhone中數(shù)據(jù)庫使用方法

首先創(chuàng)建如下格式的數(shù)據(jù)庫文件:

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

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

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

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

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

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

下面是訪問 TbNote 表格的類。

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

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

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

***我們開看看連接DB,和添加 ViewController 的處理。這一同樣不使用 Interface Builder。

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

小結(jié):深度解析iPhone數(shù)據(jù)庫使用方法的內(nèi)容介紹完了,希望通過本文的學習能對你有所幫助!

責任編輯:zhaolei 來源: 互聯(lián)網(wǎng)
相關推薦

2011-07-21 15:05:14

iPhone 數(shù)據(jù)庫

2011-08-30 13:49:57

Qt數(shù)據(jù)庫QTableView

2011-08-10 16:08:02

iPhoneProtocol協(xié)議

2011-04-13 15:44:12

SQL Server數(shù)函數(shù)

2011-08-05 16:31:47

iPhone 數(shù)據(jù)庫

2010-10-08 14:27:25

JavascriptSplit

2011-06-14 10:18:58

QThread Qt 線程

2011-08-08 14:07:49

iPhone開發(fā) 字體

2011-08-03 17:27:40

iPhone UIScrollVi

2011-08-25 17:49:14

MySQLmysqlcheck

2011-08-18 13:37:57

iPhone項目靜態(tài)庫

2011-08-29 14:44:56

DBLINK

2011-03-30 10:41:11

C++數(shù)據(jù)庫

2011-05-17 16:20:46

C++

2011-08-02 14:29:06

SQL Server數(shù)Substring函數(shù)

2011-08-02 16:16:08

iPhone開發(fā) SQLite 數(shù)據(jù)庫

2011-05-24 13:06:14

數(shù)據(jù)庫設計敏捷

2013-06-08 17:09:35

Android開發(fā)移動開發(fā)XML解析

2011-08-22 10:47:09

SQL Server流水號

2011-08-29 15:58:51

Lua函數(shù)
點贊
收藏

51CTO技術棧公眾號