日期:2014-05-16 浏览次数:20638 次
?
?
?
iPhone开发进阶(9)--- 用SQLite管理数据库
今天我们来看看 iPhone 中数据库的使用方法。iPhone 中使用名为 SQLite 的数据库管理系统。它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它 占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多 程序语言相结合,比如Tcl、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来 讲,它的处理速度比他们都快。
其使用步骤大致分为以下几步:
$ sqlite3 sample.db sqlite> CREATE TABLE TEST( ...> id INTEGER PRIMARY KEY, ...> name VARCHAR(255) ...> );
?
简单地使用上面的语句生成数据库文件后,用一个图形化SQLite管理工具,比如 Lita 来管理还是很方便的。
然后将文件(sample.db)添加到工程中。
首先添加 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
?
使用 SQL 操作数据库的代码在程序库的 fmdb.m 文件中大部分都列出了、只是连接数据库文件的时候需要注意 — 执行的时候,参照的数据库路径位于 Document 目录下,之前把刚才的 sample.db 文件拷贝过去就好了。
位置如下 /Users/xxxx/Library/Application Support/iPhone Simulator/User/Applications/xxxx/Documents/sample.db
?
以下为链接数据库时的代码:
BOOL success;
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
success = [fm fileExistsAtPath:writableDBPath];
if(!success){
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!success){
NSLog([error localizedDescription]);
}
}
// 连接DB
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
if ([db open]) {
[db setShouldCacheStatements:YES];
// INSERT
[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];
// SELECT
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 的形式来访问数据库的使用方法,代码整体构造如下。
?

?首先创建如下格式的数据库文件:
$ sqlite3 sample.db sqlite> CREATE TABLE TbNote( ...> id INTEGER PRIMARY KEY, ...> title VARCHAR(255), ...> body VARCHAR(255) ...> );