首页 > 代码库 > FMDB简单使用
FMDB简单使用
#import "ViewController.h"
#import "FMDB.h"
@interface ViewController ()
- (IBAction)insert;
- (IBAction)update;
- (IBAction)delete;
- (IBAction)select;
@property (nonatomic, strong) FMDatabase *db;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 获得数据库文件的路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepath = [docPath stringByAppendingPathComponent:@"s.sqlite"];
// 通过数据文件路径创建数据库对象
self.db = [FMDatabase databaseWithPath:filepath];
//打开数据库
if ([self.db open]) {
NSLog(@"打开数据库成功");
//创表
BOOL success = [self.db executeUpdate:@"create table if not exists t_student (id integer primary key autoincrement, name text not null, age integer not null);"];
if (success) {
NSLog(@"创表成功");
} else {
NSLog(@"创表失败");
}
} else {
NSLog(@"打开数据库失败");
}
}
- (IBAction)insert {
for (int i = 0; i<100; i++) {
NSString *name = [NSString stringWithFormat:@"cxs-%d", i];
int age = arc4random_uniform(100);
[self.db executeUpdate:@"insert into t_student (name, age) values(?, ?);", name, @(age)];
}
}
- (IBAction)update {
[self.db executeUpdate:@"update t_student set name = ? where age < ?;", @"cxs-3", @50];
}
- (IBAction)delete {
[self.db executeUpdate:@"delete from t_student where age < ?;", @50];
}
- (IBAction)select {
// 查询数据, 获得查询结果集
FMResultSet *set = [self.db executeQuery:@"select * from t_student where name like ?;", @"%cxs-5%"];
//从结果集里面取出数据
while ([set next]) {
// 取出当期指向的那行数据
NSString *name = [set stringForColumn:@"name"];
int age = [set intForColumn:@"age"];
NSLog(@"%@ - %d", name, age);
}
}