http://blog.sina.com.cn/s/blog_7b9d64af01018afm.html
一、什么是SQLite?
SQLite是一款轻型的数据库,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。
二、为什么要使用SQLite?
iPhone开发中可以使用SQLite来存储数据。如果你的应用程序要持久化数据,那SQLite将是一种不错的选择。
三、如何让应用程序得到SQLite的支持?
在项目中引用libsqlite3 .dylib 库
四、如何使用SQLite?
这个问题上,你也可以重新进行SQLite数据库操作的相关底层类。但是,已经有了一个第三方类来操作SQLite。
找个第三方类库叫”FMDB“。可以下载下来,然后添加到你的项目中去。
五、操作实例
1、新建数据库表,并插入数据
// 保存按钮事件
-(IBAction) btnSave:(id)sender{
// 要保存的数据
NSString *strName=txtName.text;
NSString *strAge=txtAge.text;
NSString *strPhone=txtAge.text;
// 使用FMDB存储数据
// 确定数据库路径
PathHelper *pathHelper=[[PathHelper alloc] init];
NSString *dbPath = [pathHelper getPhyPathByFileName:@"Friend.db"];// 获得数据库路径
FMDatabase *db= [FMDatabase databaseWithPath:dbPath] ;//创建数据库实例 db 这里说明下:如果路径中不存在"Friend.db"的文件,sqlite会自动创建"Friend.db"
// 打开数据库
if (![db open]) {
NSLog(@"Could not open db.");
return ;
}
// 创建表
if ([db executeUpdate:@"CREATE TABLE User (Name text,Age text,Phone text)"]) {
NSLog(@"creat table success");
}else {
NSLog(@"creat table false");
}
// 插入数据
[db executeUpdate:@"INSERT INTO User (Name,Age,Phone) VALUES (?,?,?)",strName,strAge,strPhone];
[db close];
// 提示
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
message:@"保存成功!"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
[pathHelper release];
[alert release];
}
2、更新数据
// 更新信息,按钮事件
-(void) btnUpdate:(id)sender{
// 数据库操作
PathHelper *pathHelper=[[PathHelper alloc] init];
NSString *dbPath = [pathHelper getPhyPathByFileName:@"Friend.db"];// 获得数据库路径
FMDatabase *db= [FMDatabase databaseWithPath:dbPath];
// 打开数据库链接
if (![db open]) {
NSLog(@"Could not open db.");
return ;
}
BOOL success=[db executeUpdate:@"UPDATE User SET Age = ?,Phone=? WHERE Name = ?",txtAge.text,txtPhone.text,txtName.text];
if (success) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
message:@"更新成功!"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
[alert release];
}else {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
message:@"更新失败!"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}