用SQLite管理数据库.docx
《用SQLite管理数据库.docx》由会员分享,可在线阅读,更多相关《用SQLite管理数据库.docx(16页珍藏版)》请在冰点文库上搜索。
用SQLite管理数据库
iPhone开发进阶(9)---用SQLite管理数据库
今天我们来看看iPhone中数据库的使用方法。
iPhone中使用名为SQLite的数据库管理系统。
它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。
它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。
其使用步骤大致分为以下几步:
1创建DB文件和表格
2添加必须的库文件(FMDBforiPhone,libsqlite3.0.dylib)
3通过FMDB的方法使用SQLite
创建DB文件和表格
1
2
3
4
5
$sqlite3sample.db
sqlite>CREATETABLETEST(
...>idINTEGERPRIMARYKEY,
...>nameVARCHAR(255)
...>);
简单地使用上面的语句生成数据库文件后,用一个图形化SQLite管理工具,比如Lita来管理还是很方便的。
然后将文件(sample.db)添加到工程中。
添加必须的库文件(FMDBforiPhone,libsqlite3.0.dylib)
首先添加Apple提供的sqlite操作用程序库ibsqlite3.0.dylib到工程中。
位置如下
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS${VER}.sdk/usr/lib/libsqlite3.0.dylib
这样一来就可以访问数据库了,但是为了更加方便的操作数据库,这里使用FMDBforiPhone。
1
svncofmdb
如上下载该库,并将以下文件添加到工程文件中:
FMDatabase.h
FMDatabase.m
FMDatabaseAdditions.h
FMDatabaseAdditions.m
FMResultSet.h
FMResultSet.m
通过FMDB的方法使用SQLite
使用SQL操作数据库的代码在程序库的fmdb.m文件中大部分都列出了、只是连接数据库文件的时候需要注意—执行的时候,参照的数据库路径位于Document目录下,之前把刚才的sample.db文件拷贝过去就好了。
位置如下
/Users/xxxx/Library/ApplicationSupport/iPhoneSimulator/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
BOOLsuccess;
NSError*error;
NSFileManager*fm=[NSFileManagerdefaultManager];
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documentsDirectory=[pathsobjectAtIndex:
0];
NSString*writableDBPath=[documentsDirectorystringByAppendingPathComponent:
@"sample.db"];
success=[fmfileExistsAtPath:
writableDBPath];
if(!
success){
NSString*defaultDBPath=[[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:
@"sample.db"];
success=[fmcopyItemAtPath:
defaultDBPathtoPath:
writableDBPatherror:
&error];
if(!
success){
NSLog([errorlocalizedDescription]);
}
}
//连接DB
FMDatabase*db=[FMDatabasedatabaseWithPath:
writableDBPath];
if([dbopen]){
[dbsetShouldCacheStatements:
YES];
//INSERT
[dbbeginTransaction];
inti=0;
while(i++<20){
[dbexecuteUpdate:
@"INSERTINTOTEST(name)values(?
)",[NSStringstringWithFormat:
@"number%d",i]];
if([dbhadError]){
NSLog(@"Err%d:
%@",[dblastErrorCode],[dblastErrorMessage]);
}
}
[dbcommit];
//SELECT
FMResultSet*rs=[dbexecuteQuery:
@"SELECT*FROMTEST"];
while([rsnext]){
NSLog(@"%d%@",[rsintForColumn:
@"id"],[rsstringForColumn:
@"name"]);
}
[rsclose];
[dbclose];
}else{
NSLog(@"Couldnotopendb.");
}
接下来再看看用DAO的形式来访问数据库的使用方法,代码整体构造如下。
首先创建如下格式的数据库文件:
1
2
3
4
5
6
$sqlite3sample.db
sqlite>CREATETABLETbNote(
...>idINTEGERPRIMARYKEY,
...>titleVARCHAR(255),
...>bodyVARCHAR(255)
...>);
创建DTO(DataTransferObject)
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
//TbNote.h
#import
@interfaceTbNote:
NSObject{
intindex;
NSString*title;
NSString*body;
}
@property(nonatomic,retain)NSString*title;
@property(nonatomic,retain)NSString*body;
-(id)initWithIndex:
(int)newIndexTitle:
(NSString*)newTitleBody:
(NSString*)newBody;
-(int)getIndex;
@end
//TbNote.m
#import"TbNote.h"
@implementationTbNote
@synthesizetitle,body;
-(id)initWithIndex:
(int)newIndexTitle:
(NSString*)newTitleBody:
(NSString*)newBody{
if(self=[superinit]){
index=newIndex;
self.title=newTitle;
self.body=newBody;
}
returnself;
}
-(int)getIndex{
returnindex;
}
-(void)dealloc{
[titlerelease];
[bodyrelease];
[superdealloc];
}
@end
创建DAO(DataAccessObjects)
这里将FMDB的函数调用封装为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
//BaseDao.h
#import
@classFMDatabase;
@interfaceBaseDao:
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"
@implementationBaseDao
@synthesizedb;
-(id)init{
if(self=[superinit]){
//由AppDelegate取得打开的数据库
SqlSampleAppDelegate*appDelegate=(SqlSampleAppDelegate*)[[UIApplicationsharedApplication]delegate];
db=[[appDelegatedb]retain];
}
returnself;
}
//子类中实现
-(NSString*)setTable:
(NSString*)sql{
returnNULL;
}
-(void)dealloc{
[dbrelease];
[superdealloc];
}
@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
#import
#import"BaseDao.h"
@interfaceTbNoteDao:
BaseDao{
}
-(NSMutableArray*)select;
-(void)insertWithTitle:
(NSString*)titleBody:
(NSString*)body;
-(BOOL)updateAt:
(int)indexTitle:
(NSString*)titleBody:
(NSString*)body;
-(BOOL)deleteAt:
(int)index;
@end
//TbNoteDao.m
#import"FMDatabase.h"
#import"FMDatabaseAdditions.h"
#import"TbNoteDao.h"
#import"TbNote.h"
@implementationTbNoteDao
-(NSString*)setTable:
(NSString*)sql{
return[NSStringstringWithFormat:
sql,@"TbNote"];
}
//SELECT
-(NSMutableArray*)select{
NSMutableArray*result=[[[NSMutableArrayalloc]initWithCapacity:
0]autorelease];
FMResultSet*rs=[dbexecuteQuery:
[selfsetTable:
@"SELECT*FROM%@"]];
while([rsnext]){
TbNote*tr=[[TbNotealloc]
initWithIndex:
[rsintForColumn:
@"id"]
Title:
[rsstringForColumn:
@"title"]
Body:
[rsstringForColumn:
@"body"]
];
[resultaddObject:
tr];
[trrelease];
}
[rsclose];
returnresult;
}
//INSERT
-(void)insertWithTitle:
(NSString*)titleBody:
(NSString*)body{
[dbexecuteUpdate:
[selfsetTable:
@"INSERTINTO%@(title,body)VALUES(?
?
)"],title,body];
if([dbhadError]){
NSLog(@"Err%d:
%@",[dblastErrorCode],[dblastErrorMessage]);
}
}
//UPDATE
-(BOOL)updateAt:
(int)indexTitle:
(NSString*)titleBody:
(NSString*)body{
BOOLsuccess=YES;
[dbexecuteUpdate:
[selfsetTable:
@"UPDATE%@SETtitle=?
body=?
WHEREid=?
"],title,body,[NSNumbernumberWithInt:
index]];
if([dbhadError]){
NSLog(@"Err%d:
%@",[dblastErrorCode],[dblastErrorMessage]);
success=NO;
}
returnsuccess;
}
//DELETE
-(BOOL)deleteAt:
(int)index{
BOOLsuccess=YES;
[dbexecuteUpdate:
[selfsetTable:
@"DELETEFROM%@WHEREid=?
"],[NSNumbernumberWithInt:
index]];
if([dbhadError]){
NSLog(@"Err%d:
%@",[dblastErrorCode],[dblastErrorMessage]);
success=NO;
}
returnsuccess;
}
-(void)dealloc{
[superdealloc];
}
@end
为了确认程序正确,我们添加一个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
#import
@classTbNoteDao;
@interfaceNoteController:
UIViewController{
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"
@implementationNoteController
@synthesizemyTableView,tbNoteDao,record;
-(id)initWithNibName:
(NSString*)nibNameOrNilbundle:
(NSBundle*)nibBundleOrNil{
if(self=[superinitWithNibName:
nibNameOrNilbundle:
nibBundleOrNil]){
tbNoteDao=[[TbNoteDaoalloc]init];
[tbNoteDaoinsertWithTitle:
@"TESTTITLE"Body:
@"TESTBODY"];
//[tbNoteDaoupdateAt:
1Title:
@"UPDATETEST"Body:
@"UPDATEBODY"];
//[tbNoteDaodeleteAt:
1];
record=[[tbNoteDaoselect]retain];
}
returnself;
}
-(void)viewDidLoad{
[superviewDidLoad];
myTableView=[[UITableViewalloc]initWithFrame:
[[UIScreenmainScreen]applicationFrame]];
myTableView.delegate=self;
myTableView.dataSource=self;
self.view=myTableView;
}
-(NSInteger)numberOfSectionsInTableView:
(UITableView*)tableView{
return1;
}
-(NSInteger)tableView:
(UITableView*)tableViewnumberOfRowsInSection:
(NSInteger)section{
return[recordcount];
}
-(UITableViewCell*)tableView:
(UITableView*)tableViewcellForRowAtIndexPath:
(NSIndexPath*)indexPath{
staticNSString*CellIdentifier=@"Cell";
UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:
CellIdentifier];
if(cell==nil){
cell=[[[UITableViewCellalloc]initWithFrame:
CGRectZeroreuseIdentifier:
CellIdentifier]autorelease];
}
TbNote*tr=(TbNote*)[recordobjectAtIndex:
indexPath.row];
cell.text=[NSStringstringWithFormat:
@"%i%@",[trgetIndex],tr.title];
returncell;
}
-(void)didReceiveMemoryWarning{
[superdidReceiveMemoryWarning];
}
-(void)dealloc{
[superdealloc];
}
@end
最后我们开看看连接DB,和添加ViewController的处理。
这一同样不使用InterfaceBuilder。
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