iPhone中数据库使用方法

移动开发 iOS
本文介绍的是iPhone中数据库使用方法,主要讲述了iPhone 中使用名为 SQLite 的数据库管理系统,先来看内容。

iPhone数据库使用方法是本文要介绍的内容,直接进入话题介绍,iPhone 中使用名为 SQLite 的数据库管理系统。它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,

在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、PHP、Java 等,还有 ODBC 接口,同样比起 Mysql、PostgreSQL 这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。

其使用步骤大致分为以下几步:

1. 创建DB文件和表格

2. 添加必须的库文件(FMDB for iPhone, libsqlite3.0.dylib)

3. 通过 FMDB 的方法使用 SQLite

创建DB文件和表格

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

简单地使用上面的语句生成数据库文件后,用一个图形化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 

这样一来就可以访问数据库了,但是为了更加方便的操作数据库,这里使用 FMDB for iPhone。

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 操作数据库的代码在程序库的 fmdb.m 文件中大部分都列出了、只是连接数据库文件的时候需要注意 — 执行的时候,参照的数据库路径位于 Document 目录下,之前把刚才的 sample.db 文件拷贝过去就好了。

位置如下
/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.");  

以下为链接数据库时的代码:

接下来再看看用 DAO 的形式来访问数据库的使用方法,代码整体构造如下。如图:

iPhone中数据库使用方法

首先创建如下格式的数据库文件:

  1. $ sqlite3 sample.db  
  2. sqlite> CREATE TABLE TbNote(  
  3.    ...>  id INTEGER PRIMARY KEY,  
  4.    ...>  title VARCHAR(255),  
  5.    ...>  body VARCHAR(255)  
  6.    ...> );  
  7. 创建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 

创建DAO(Data Access Objects)

这里将 FMDB 的函数调用封装为 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 取得打开的数据库  
  26.     SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];  
  27.     db = [[appDelegate db] retain];  
  28.   }  
  29.   return self;  
  30. }  
  31. // 子类中实现  
  32. -(NSString *)setTable:(NSString *)sql{  
  33.   return NULL;  
  34. }  
  35. - (void)dealloc {  
  36.   [db release];  
  37.   [super dealloc];  
  38. }  
  39. @end 

下面是访问 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 

为了确认程序正确,我们添加一个 UITableView。使用 initWithNibName 测试 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 

***我们开看看连接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 

小结:iPhone数据库使用方法的内容介绍完了,希望本文对你有所帮助。

转自 http://www.yifeiyang.net/iphone-developer-advanced-9-management-database-using-sqlite/

责任编辑:zhaolei 来源: Cocoa China
相关推荐

2011-08-11 17:00:33

iPhone数据库SQLite

2011-08-30 13:49:57

Qt数据库QTableView

2011-04-13 15:44:12

SQL Server数函数

2011-08-10 16:08:02

iPhoneProtocol协议

2011-08-05 16:31:47

iPhone 数据库

2011-08-25 17:49:14

MySQLmysqlcheck

2011-08-08 14:07:49

iPhone开发 字体

2011-08-03 17:27:40

iPhone UIScrollVi

2011-08-29 14:44:56

DBLINK

2011-05-17 16:20:46

C++

2011-03-30 10:41:11

C++数据库

2011-08-02 14:29:06

SQL Server数Substring函数

2011-08-02 16:16:08

iPhone开发 SQLite 数据库

2011-08-22 10:47:09

SQL Server流水号

2011-07-26 16:33:56

iPhone Delegate

2011-07-27 10:16:41

iPhone SQLite 数据库

2009-12-22 11:24:37

ADO.NET数据库

2011-02-28 17:00:50

ACCESS数据库

2011-08-05 14:58:58

iPhone CoreAnimat 动画

2011-07-21 15:20:31

iPhone SDK 多线程
点赞
收藏

51CTO技术栈公众号