iPhone开发进阶(9)— 用SQLite管理数据库
- 博主:易飞扬
- 原文链接 : http://www.yifeiyang.net/iphone-developer-advanced-9-management-database-using-sqlite/
- 转载请保留上面文字。
iPhone开发进阶(9)--- 用SQLite管理数据库
今天我们来看看 iPhone 中数据库的使用方法。iPhone 中使用名为 SQLite 的数据库管理系统。它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。
其使用步骤大致分为以下几步:
- 创建DB文件和表格
- 添加必须的库文件(FMDB for iPhone, libsqlite3.0.dylib)
- 通过 FMDB 的方法使用 SQLite
-
创建DB文件和表格
简单地使用上面的语句生成数据库文件后,用一个图形化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。如上下载该库,并将以下文件添加到工程文件中:
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
以下为链接数据库时的代码:
接下来再看看用 DAO 的形式来访问数据库的使用方法,代码整体构造如下。
首先创建如下格式的数据库文件:
-
创建DTO(Data Transfer Object)
-
创建DAO(Data Access Objects)
这里将 FMDB 的函数调用封装为 DAO 的方式。
下面是访问 TbNote 表格的类。
为了确认程序正确,我们添加一个 UITableView。使用 initWithNibName 测试 DAO。
最后我们开看看连接DB,和添加 ViewController 的处理。这一同样不使用 Interface Builder。
相关文章
- iPhone开发之深入浅出 (5) --- ARC之Outlet与弱引用 - (2012-03-08)
- iPhone开发之深入浅出 (4) --- ARC之循环参照 - (2012-03-01)
- iPhone开发之深入浅出 (3) --- ARC之前世今生 - (2012-02-19)
- iPhone开发之深入浅出 (2) --- ARC之@property使用 - (2012-01-04)
- iPhone开发之深入浅出 (1) --- ARC是什么 - (2012-01-01)
- iPhone开发技巧之调试篇(3)--- 程序Crash后的调试技巧 - (2011-11-06)
- iPhone开发之游戏篇(3)--- cocos2d的Actions构成 - (2010-07-05)
- iPhone开发之游戏篇(2) --- cocos2d的Actions - (2010-07-03)
- iPhone开发之游戏篇(1) --- cocos2d的基本概念 - (2010-07-01)
- iPhone开发进阶(11)--- 多线程的使用与注意事项 - (2010-03-09)
- iPhone开发进阶(10)--- 在程序中使用 GPS - (2010-03-07)
- iPhone开发进阶(8)--- 检测屏幕触摸事件 - (2010-03-04)
- iPhone开发进阶(7)--- 利用ModalViewController切换View - (2010-03-02)
- iPhone开发进阶(6)--- 编程定制UIButton - (2010-02-27)
- iPhone开发进阶(5) --- 编程定制UIViewController - (2010-02-25)
- iPhone开发进阶(4) --- 使用Makefile自动编译iPhone程序 - (2010-02-23)
- iPhone开发进阶(3) --- iPhone应用程序的启动过程 - (2010-02-21)
- iPhone开发进阶(2) --- iPhone应用程序/项目的构成 - (2010-02-19)
- iPhone开发进阶(1) --- 深入理解iPhone OS/SDK与Objective-C 2.0 - (2010-02-17)
- iPhone、Android、Symbian … 移动设备应用程序开发的趋势与对策 - (2010-02-14)
- 使用org-mode来GTD(3)--- iPhone中使用org-mode - (2010-02-06)
- iPhone开发入门(11)--- 在App Store上发布程序 - (2010-01-21)
- iPhone开发入门(10)--- 设备上运行程序 - (2010-01-19)
- iPhone开发入门(9)--- 实际开发中的应用技巧 - (2010-01-16)
- iPhone开发入门(8)--- 程序画面与控件调整 - (2010-01-05)