看看 iPhone 中数据库的使用方法。iPhone 中使用名为 SQLite 的数据库管理系统。它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。
其使用步骤大致分为以下几步:
- 创建DB文件和表格
- 添加必须的库文件(FMDB for iPhone,libsqlite3.0.dylib)
- 通过 FMDB 的方法使用 SQLite
创建DB文件和表格
|
1
2
3
4
5
$ sqlite3 sample.db
sqlite> CREATE TABLE TEST(
...> id INTEGER PRIMARY KEY,...> name VARCHAR(255)
...> );
简单地使用上面的语句生成数据库文件后,用一个图形化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
这样一来就可以访问数据库了,但是为了更加方便的操作数据库,这里使用 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 文件拷贝过去就好了。
位置如下
/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];
writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
success = [fm fileExistsAtPath:writableDBPath];
if(!success){
defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!success){
NSLog([error localizedDescription]);
}
}
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
if ([db open]) {
[db setShouldCacheStatements:YES];
[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];
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
#import <Foundation/Foundation.h>
@interface TbNote : NSObject {
index;
title;
body;
}
@property (nonatomic,retain) title;
@property (nonatomic,212); font-weight:bold">body;
- (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(newBody;
- (int)getIndex;
@end
"TbNote.h"
@implementation TbNote
@synthesize title,body;
- (newBody{
if(self = [super init]){
index = newIndex;
self.title = newTitle;
self.body = newBody;
}
return self;
}
- (getIndex{
return index;
}
- (void)dealloc {
[title release];
[body release];
[super dealloc];
}
@end
创建DAO(Data Access Objects)
这里将 FMDB 的函数调用封装为 DAO 的方式。
BaseDao.h
@class FMDatabase;
BaseDao : FMDatabase *db;
}
@property (nonatomic,212); font-weight:bold">db;
-(NSString *)setTable:(sql;
BaseDao.m
"SqlSampleAppDelegate.h"
"FMDatabase.h"
"FMDatabaseAdditions.h"
"BaseDao.h"
BaseDao
db;
- (init{
super init]){
SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];
db = [[appDelegate db] retain];
}
self;
}
-(sql{
return NULL;
}
- (dealloc {
[db release];
[@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
<Foundation/Foundation.h>
TbNoteDao : BaseDao {
}
-(NSMutableArray *)select;
-(insertWithTitle:(title body;
-(BOOL)updateAt:(index deleteAt:(index;
TbNoteDao.m
"TbNoteDao.h"
TbNoteDao
-(return [NSString stringWithFormat:sql,@"TbNote"];
}
-(select{
NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
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;
}
-(body{
[db executeUpdate:["INSERT INTO %@ (title,body) VALUES (?,?)"],title,body];
if ([db hadError]) {
NSLog(@UPDATE
-(body{
success = YES;
[db executeUpdate:["UPDATE %@ SET title=?,body=? WHERE id=?"],body,50); font-weight:bold">NSNumber numberWithInt:index]];
NO;
}
return success;
}
- (index{
"DELETE FROM %@ WHERE id = ?"],114); font-weight:bold">return success;
}
- (dealloc {
[ 为了确认程序正确,我们添加一个 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
<UIKit/UIKit.h>
TbNoteDao;
NoteController : UIViewController <UITableViewDataSource,50); font-weight:bold">UITableViewDelegate>{
UITableView *myTableView;
TbNoteDao *tbNoteDao;
record;
}
@property (nonatomic,212); font-weight:bold">myTableView;
@property (nonatomic,212); font-weight:bold">tbNoteDao;
@property (nonatomic,212); font-weight:bold">record;
NoteController.m
"NoteController.h"
NoteController
myTableView,50); font-weight:bold">tbNoteDao,50); font-weight:bold">record;
- (initWithNibName:(nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
tbNoteDao = [[TbNoteDao alloc] init];
[tbNoteDao insertWithTitle:@"TEST TITLE" Body:@"TEST BODY"];
record = [[tbNoteDao select] retain];
}
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;
}
- (tableView:(tableView numberOfRowsInSection:(NSInteger)section {
return [record count];
}
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
tr = (TbNote *)[record objectAtIndex:indexPath.row];
cell.text = ["%i %@",[tr getIndex],tr.title];
return cell;
}
- (didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- ( 最后我们开看看连接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
SqlSampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
window;
@property (nonatomic,212); font-weight:bold">db;
- (initDatabase;
- (closeDatabase;
SqlSampleAppDelegate.m
"NoteController.h"
SqlSampleAppDelegate
window;
@synthesize 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];
}
- (initDatabase{
success;
error;
NSFileManager defaultManager];
YES);
documentsDirectory = [paths objectAtIndex:0];
"sample.db"];
success = [fm fileExistsAtPath:writableDBPath];
"sample.db"];
success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!success){
NSLog([error localizedDescription]);
}
success = if(success){
db = [[FMDatabase databaseWithPath:writableDBPath] retain];
if ([db open]) {
[db setShouldCacheStatements:YES];
}else{
NSLog(@"Failed to open database.");
success = NO;
}
}
void) closeDatabase{
[db close];
}
- (dealloc {
[db release];
[window release];
[@end
转自:http://www.yifeiyang.net/iphone-developer-advanced-9-management-database-using-sqlite/
http://marshal.easymorse.com/archives/3349 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!