1. 预备知识
读者需要有一定的SQLite数据库知识,懂得基本的SQL语句,掌握OSX系统terminal终端 以及 XCode编译器 的基本操作。
2. 创建数据库
打开 Applications-Utilities-Terminal,可见终端窗口。
假设当前系统用户为Smitty,可在终端窗口内键入如下命令:
cd /Users/Smitty/Documents
mkdir SQLiteDemo
cd SQLiteDemo
sqlite3 PersonDatabase.sql
至此,你已经在/Users/lookaflyingdonkey/Documents目录下创建了一个新的目录SQLiteDemo,并使用 sqlite3命令开启了SQLite终端,准备建立数据库结构并输入数据。
举例来说,若我们要建立的数据库表person需要有如下结构:唯一的id值,名字,职位描述,头像图片地址,那么下列命令将创建这个表,并添加几个人的纪录。
CREATE TABLE person (id INTEGER PRIMARY KEY, name VARCHAR(50), title TEXT, icon VARCHAR(255) );
INSERT INTO person (name, title, icon) VALUES('Peter','handy man','http://dblog.com.au/wp-content/elephant.jpg');
INSERT INTO person (name, title, icon) VALUES('Susan','manager','http://dblog.com.au/wp-content/monkey.jpg');
INSERT INTO person (name, title, icon) VALUES('Wilson','developer','http://dblog.com.au/wp-content/kangaroo.jpg');
执行完这几步后,可运行命令"SELECT * FROM person;",检查数据库中是否已存在上面插入的数据。一旦确认一切正常,可用命令".quit"退出sqlite 命令行模式。
3. 创建项目
现在让我门创建Xcode项目。
首先在Xcode中选择创建一个新的” Navigation-Based Application“
输入项目名称"SQLiteDemo",由于之前在同一位置创建了同名目录,Xcode将会询问是否覆盖已经存在的目录SQLiteDemo,选则是。这将使项目目录结构如下图所示。
4. 将SQLite框架和PersonDatabas数据库导入项目
首先我们需要将SQLite库引入项目。请右键点击左部菜单中的"Frameworks"目录,选择“Add > Existing Frameworks…”,
然后在本地目录中选择“/Developer/Platforms/iPhoneOS.platform/Developer /SDKs/iPhoneOS3.0.sdk/usr/lib/”,找到“libsqlite3.0.dylib”文件并双击。
一个弹出窗口将出现,点击其中“Add”按钮将库添加入项目中。
我们也需要将PersonDatabas 数据库导入Resources目录。请右键点击“Resources”目录,选择“Add > Existing Files…”,在本地目录中选择“/Users/Smitty/Documents/SQLiteDemo/”, 双击PersonDatabase.sql文件,点击弹出窗口中的“Add”按钮将其导入当前项目。
5. 开始编程
首先创建一个Person类。右键点击“Classes”目录,选择“Add > New File…”,在弹出窗口中选择“iPhone OS > Cocoa Touch Class > Objective-C class > NSObject” 并点击“Next”按钮。在下一窗口中,设置File Name为“Person.m”。点击“Finish”按钮完成创建。
修改Classes/Person.h为:
@interface Person : NSObject {
NSString *name;
NSString *title;
NSString *iconURL;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *iconURL;
-(id)initWithName:(NSString *)n title:(NSString *)t url:(NSString *)u;
@end
修改Classes/Person.m为:
#import "Person.h"
@implementation Person
@synthesize name, title, iconURL;
-(id)initWithName:(NSString *)n title:(NSString *)t url:(NSString *)u {
self.name=n;
self.title=t;
self.iconURL=u;
return self;
}
@end
修改Other Sources/main.m为:
#import
#import "Person.h"
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//setup database name.
NSString *databaseName = @"PersonDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDirstringByAppendingPathComponent:databaseName];
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
BOOL success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(!success){
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
// Query the database for all person records and construct the "person" array
sqlite3 *database;
// Init the animals Array
NSMutableArray *personArr = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from person";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aTitle = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 2)];
NSString *aIconUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new animal object with the data from the database
Person *person = [[Person alloc] initWithName:aName title:aTitle url:aIconUrl];
// Add the animal object to the animals Array
[personArr addObject:person];
[person release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
for (Person *tmpPerson in personArr) {
NSLog(@"You can see %@ %@'s icon at %@", tmpPerson.title, tmpPerson.name, tmpPerson.iconURL);
[tmpPerson release];
}
NSLog(@"Done.");
[personArr release];
[fileManager release];
[pool release];
return (0);
}
6. 编译执行
完成修改后,运行“Build > Build and Run”, 关掉弹出的iPhone Simulator窗口,选择"Run > Console" 打开控制台,可看到如下输出信息。
参考:
http://www.cnblogs.com/AlexLiu/archive/2010/04/21/1716740.html