本文共 3043 字,大约阅读时间需要 10 分钟。
Sqlite3 是 iPhone-app 开发中常用的本地数据库解决方案,适用于简单的增删改查操作。其特点是轻量级且无服务器,操作流程如下:
在 Xcode 项目设置中,进入 Build Phases > Add/Library
,点击右上角的 +
按钮,选择 Sqlite3
库进行添加。
// 数据库路径获取NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"person.sqlite"];sqlite3_open(path.UTF8String, &_db);// 创建数据库表NSString *createTableSql = @"create table if not exists t_person (id integer primary key autoincrement, name text not null, age integer default 10)";if (sqlite3_exec(_db, createTableSql.UTF8String, NULL, NULL, NULL) == SQLITE_OK) { NSLog(@"创建表成功");}
插入数据:
NSString *insertSql = @"insert into t_person (name, age) values('zhangsan', 15)";if (sqlite3_exec(_db, insertSql.UTF8String, NULL, NULL, NULL) == SQLITE_OK) { NSLog(@"插入成功");}
删除数据:
NSString *deleteSql = @"delete from t_person where age > 5";if (sqlite3_exec(_db, deleteSql.UTF8String, NULL, NULL, NULL) == SQLITE_OK) { NSLog(@"删除成功");}
更新数据:
NSString *updateSql = @"update t_person set name='lisi' where age > 5";if (sqlite3_exec(_db, updateSql.UTF8String, NULL, NULL, NULL) == SQLITE_OK) { NSLog(@"更新成功");}
查询数据:
NSString *querySql = @"select name, age from t_person";sqlite3_stmt *stmt = nil;if (sqlite3_prepare_v2(_db, querySql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) { while (sqlite3_step(stmt) == SQLITE_ROW) { NSString *name = sqlite3_column_text(stmt, 0); int age = sqlite3_column_int(stmt, 1); NSLog(@"姓名: %@, 年龄: %d", name, age); }}
FMDB 是一个流行的第三方 SQLite 库框架,简化了 Sqlite3 的使用,适合快速开发需求。其优势包括线程安全和易用性。
在项目中添加 FMDB.framework,注意包含 #import "FMDB.h"
头文件。
// 数据库路径NSString *fmdbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sqlite");FMDatabase *fmdb = [FMDatabase databaseWithPath:fmdbPath];[fmdb open];// 创建表if ([fmdb executeUpdate:@"create table if not exists t_person (id integer primary key autoincrement, name text not null, age integer default 10)"]) { NSLog(@"创建表成功");}
插入数据:
[self.database executeUpdate:@"insert into t_person (name, age) values('zhangsan', 15)"];
删除数据:
[self.database executeUpdate:@"delete from t_person where age > 5"];
更新数据:
[self.database executeUpdate:@"update t_person set name='lisi' where age > 5"];
查询数据:
[self.database executeQuery:@"select name, age from t_person"];while ([result next]) { NSString *name = [result stringForColumnIndex:0]; int age = [result intForColumnIndex:1]; NSLog(@"姓名: %@", name, age);}
FMDB 提供线程安全操作,推荐使用 FMDatabaseQueue
:
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fmdbPath];// 线程安全写法[queue inDatabase:^{ // 在数据库操作 [数据库.open];}];// 查询操作[queue inDatabase:^{ // 查询代码}];
[queue inDatabase:^{ [database beginTransaction]; // 同一事务内多个操作}]);
事务可以通过 commit
或 rollback
管理,并可通过 inTransaction
判断事务状态。
通过以上方法,您可以快速实现 iOS 应用中的本地数据存储需求,选择 Sqlite3 或 FMDB 根据项目复杂度和开发需求进行选择。
转载地址:http://aevrz.baihongyu.com/