FMDB 简单实用
2016-05-22 00:00
253 查看
@interface ViewController ()
// 数据库实例对象.
@property(nonatomic ,strong) FMDatabase *db;
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad];
// FMDB 框架: OC 对数据库的 C语言API 做的封装.
// FMDatabase :数据库实例.
// FMDatabaseQueue :安全的数据库队列.在多线程中使用数据库的时候,为了保证数据的安全性,必须使用 FMDatabaseQueue;
// FMResultSet :在数据库中查询到的数据,都存放在 FMResultSet 中.
// FMDB 原理: 除查询数据之外的所有的数据库操作都叫更新.executeUpdate
// FMDB 中查询数据使用: executeQuery
}
(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchesBegan");
// 所有关于数据库的函数都在 sqlte3 中. 所以所有的函数都是以 sqlite3开头.
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES).lastObject;
// 定义数据库文件的位置.
NSString *fileName = [NSString stringWithFormat:@"%@/student.sqlite",path];
// 实例化数据库对象.
self.db = [FMDatabase databaseWithPath:fileName];
if ([self.db open]) {
}
}
// 数据库实例对象.
@property(nonatomic ,strong) FMDatabase *db;
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad];
// FMDB 框架: OC 对数据库的 C语言API 做的封装.
// FMDatabase :数据库实例.
// FMDatabaseQueue :安全的数据库队列.在多线程中使用数据库的时候,为了保证数据的安全性,必须使用 FMDatabaseQueue;
// FMResultSet :在数据库中查询到的数据,都存放在 FMResultSet 中.
// FMDB 原理: 除查询数据之外的所有的数据库操作都叫更新.executeUpdate
// FMDB 中查询数据使用: executeQuery
}
(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchesBegan");
// 所有关于数据库的函数都在 sqlte3 中. 所以所有的函数都是以 sqlite3开头.
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES).lastObject;
// 定义数据库文件的位置.
NSString *fileName = [NSString stringWithFormat:@"%@/student.sqlite",path];
// 实例化数据库对象.
self.db = [FMDatabase databaseWithPath:fileName];
if ([self.db open]) {
NSLog(@"数据库打开成功!"); NSString *sql = @"SELECT * FROM t_student WHERE age >18 LIMIT 0,20;"; // FMDB 查询数据 FMResultSet *sr = [self.db executeQuery:sql]; // 查看查询到的数据. while ([sr next]) { // 取出字段为 id 的数据. int myID = [sr intForColumn:@"id"]; NSString *name = [sr stringForColumn:@"name"]; int age = [sr intForColumn:@"age"]; int height = [sr intForColumn:@"height"]; NSLog(@"name:%@ id:%d age:%d height:%d",name,myID,age,height); // 将取出来的数据包装成数组或者字典.再转换成模型使用!... }
}
}
相关文章推荐