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

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

移動(dòng)開(kāi)發(fā) iOS
本文介紹的是iPhone中數(shù)據(jù)庫(kù)使用方法,主要講述了iPhone 中使用名為 SQLite 的數(shù)據(jù)庫(kù)管理系統(tǒng),先來(lái)看內(nèi)容。

iPhone數(shù)據(jù)庫(kù)使用方法是本文要介紹的內(nèi)容,直接進(jìn)入話題介紹,iPhone 中使用名為 SQLite 的數(shù)據(jù)庫(kù)管理系統(tǒng)。它是一款輕型的數(shù)據(jù)庫(kù),是遵守ACID的關(guān)聯(lián)式數(shù)據(jù)庫(kù)管理系統(tǒng),它的設(shè)計(jì)目標(biāo)是嵌入式的,而且目前已經(jīng)在很多嵌入式產(chǎn)品中使用了它,它占用資源非常的低,

在嵌入式設(shè)備中,可能只需要幾百K的內(nèi)存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統(tǒng),同時(shí)能夠跟很多程序語(yǔ)言相結(jié)合,比如 Tcl、PHP、Java 等,還有 ODBC 接口,同樣比起 Mysql、PostgreSQL 這兩款開(kāi)源世界著名的數(shù)據(jù)庫(kù)管理系統(tǒng)來(lái)講,它的處理速度比他們都快。

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

1. 創(chuàng)建DB文件和表格

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

3. 通過(guò) FMDB 的方法使用 SQLite

創(chuàng)建DB文件和表格

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

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

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

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

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

  1. /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS${VER}.sdk/usr/lib/libsqlite3.0.dylib 

這樣一來(lái)就可以訪問(wèn)數(shù)據(jù)庫(kù)了,但是為了更加方便的操作數(shù)據(jù)庫(kù),這里使用 FMDB for iPhone。

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

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

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

通過(guò) FMDB 的方法使用 SQLite

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

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

  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. // 連接DB  
  16. FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];  
  17. if ([db open]) {  
  18.   [db setShouldCacheStatements:YES];  
  19.  
  20.   // INSERT  
  21.   [db beginTransaction];  
  22.   int i = 0;  
  23.   while (i++ < 20) {  
  24.     [db executeUpdate:@"INSERT INTO TEST (name) values (?)" , [NSString stringWithFormat:@"number %d", i]];  
  25.     if ([db hadError]) {  
  26.       NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);  
  27.     }  
  28.   }  
  29.   [db commit];  
  30.   // SELECT  
  31.   FMResultSet *rs = [db executeQuery:@"SELECT * FROM TEST"];  
  32.   while ([rs next]) {  
  33.     NSLog(@"%d %@", [rs intForColumn:@"id"], [rs stringForColumn:@"name"]);  
  34.   }  
  35.   [rs close];  
  36.   [db close];  
  37. }else{  
  38.   NSLog(@"Could not open db.");  

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

接下來(lái)再看看用 DAO 的形式來(lái)訪問(wèn)數(shù)據(jù)庫(kù)的使用方法,代碼整體構(gòu)造如下。如圖:

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

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

  1. $ sqlite3 sample.db  
  2. sqlite> CREATE TABLE TbNote(  
  3.    ...>  id INTEGER PRIMARY KEY,  
  4.    ...>  title VARCHAR(255),  
  5.    ...>  body VARCHAR(255)  
  6.    ...> );  
  7. 創(chuàng)建DTO(Data Transfer Object)  
  8. //TbNote.h  
  9. #import <Foundation/Foundation.h> 
  10.  
  11. @interface TbNote : NSObject {  
  12.   int index;  
  13.   NSString *title;  
  14.   NSString *body;  
  15. }  
  16. @property (nonatomic, retain) NSString *title;  
  17. @property (nonatomic, retain) NSString *body;  
  18. - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody;  
  19. - (int)getIndex;  
  20. @end  
  21. //TbNote.m  
  22. #import "TbNote.h"  
  23. @implementation TbNote  
  24. @synthesize title, body;  
  25. - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{  
  26.   if(self = [super init]){  
  27.     index = newIndex;  
  28.     self.title = newTitle;  
  29.     self.body = newBody;  
  30.   }  
  31.   return self;  
  32. }  
  33. - (int)getIndex{  
  34.   return index;  
  35. }  
  36. - (void)dealloc {  
  37.   [title release];  
  38.   [body release];  
  39.   [super dealloc];  
  40. }  
  41. @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. @implementation BaseDao  
  22. @synthesize db;  
  23. - (id)init{  
  24.   if(self = [super init]){  
  25.     // 由 AppDelegate 取得打開(kāi)的數(shù)據(jù)庫(kù)  
  26.     SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];  
  27.     db = [[appDelegate db] retain];  
  28.   }  
  29.   return self;  
  30. }  
  31. // 子類中實(shí)現(xiàn)  
  32. -(NSString *)setTable:(NSString *)sql{  
  33.   return NULL;  
  34. }  
  35. - (void)dealloc {  
  36.   [db release];  
  37.   [super dealloc];  
  38. }  
  39. @end 

下面是訪問(wèn) TbNote 表格的類。

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

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

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

***我們開(kāi)看看連接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.  
  68. - (void) closeDatabase{  
  69.   [db close];  
  70. }  
  71.  
  72. - (void)dealloc {  
  73.   [db release];  
  74.   [window release];  
  75.   [super dealloc];  
  76. }  
  77. @end 

小結(jié):iPhone數(shù)據(jù)庫(kù)使用方法的內(nèi)容介紹完了,希望本文對(duì)你有所幫助。

轉(zhuǎn)自 http://www.yifeiyang.net/iphone-developer-advanced-9-management-database-using-sqlite/

責(zé)任編輯:zhaolei 來(lái)源: Cocoa China
相關(guān)推薦

2011-08-11 17:00:33

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

2011-08-30 13:49:57

Qt數(shù)據(jù)庫(kù)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ù)庫(kù)

2011-08-08 14:07:49

iPhone開(kāi)發(fā) 字體

2011-08-03 17:27:40

iPhone UIScrollVi

2011-08-25 17:49:14

MySQLmysqlcheck

2011-08-29 14:44:56

DBLINK

2011-05-17 16:20:46

C++

2011-03-30 10:41:11

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

2011-08-02 14:29:06

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

2011-08-02 16:16:08

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

2011-08-22 10:47:09

SQL Server流水號(hào)

2011-07-26 16:33:56

iPhone Delegate

2011-07-27 10:16:41

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

2009-12-22 11:24:37

ADO.NET數(shù)據(jù)庫(kù)

2011-08-05 14:58:58

iPhone CoreAnimat 動(dòng)畫(huà)

2011-07-21 15:20:31

iPhone SDK 多線程

2010-10-08 14:27:25

JavascriptSplit
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)