IOS操做數據庫,SQLite3和coredata是兩個很是好的選擇,可是對於咱們這些掌握了其餘數據庫語言的人來講,使用這兩中操做都會以爲不方便,SQLite3使用起來太複雜了,而使用coredata的時候卻封裝太死了,咱們須要本身些本身的數據庫語句,這時候,FMDB就是一個很是不錯的選擇sql
下面是FMDB的基本使用數據庫
在Main.storyboard中添加4個按鈕分別是(插入 , 更新,刪除 , 查詢)dom
在ViewController中atom
//spa
// ViewController.morm
//sqlite
//對象
#import "ViewController.h"rem
#import "FMDB.h"string
@interface ViewController ()
@property (nonatomic, strong) FMDatabase *db;
- (IBAction)insert;
- (IBAction)update;
- (IBAction)delete;
- (IBAction)query;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 0.得到沙盒中的數據庫文件名
NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"];
// 1.建立數據庫實例對象
self.db = [FMDatabase databaseWithPath:filename];
// 2.打開數據庫
if ( [self.db open] ) {
NSLog(@"數據庫打開成功");
// 創表
BOOL result = [self.db executeUpdate:@"create table if not exists t_student (id integer primary key autoincrement, name text, age integer);"];
if (result) {
NSLog(@"創表成功");
} else {
NSLog(@"創表失敗");
}
} else {
NSLog(@"數據庫打開失敗");
}
}
- (IBAction)insert
{
for (int i = 0; i<40; i++) {
NSString *name = [NSString stringWithFormat:@"rose-%d", arc4random() % 1000];
NSNumber *age = @(arc4random() % 100 + 1);
[self.db executeUpdate:@"insert into t_student (name, age) values (?, ?);", name, age];
}
}
- (IBAction)update
{
[self.db executeUpdate:@"update t_student set age = ? where name = ?;", @20, @"jack"];
}
- (IBAction)delete
{
}
- (IBAction)query
{
// 1.查詢數據
FMResultSet *rs = [self.db executeQuery:@"select * from t_student where age > ?;", @50];
// 2.遍歷結果集
while (rs.next) {
int ID = [rs intForColumn:@"id"];
NSString *name = [rs stringForColumn:@"name"];
int age = [rs intForColumn:@"age"];
NSLog(@"%d %@ %d", ID, name, age);
}
}
@end