//
Viewcontroller.m
04-fmdb Thread-safe usage
//
Created by Li Hongqiang on 2017/6/6.
Copyright? year Li Hongqiang . All rights reserved.
//
#import "ViewController.h"
Import Header File
#import "FMDB.h"
@interface viewcontroller ()
@property(nonatomic,strong)fmdatabasequeue *databaseq;
@end
@implementation Viewcontroller
-(void) viewdidload {
[Super viewdidload];
nsstring *path = [[nssearchpathfordirectoriesindomains(nsdocumentdirectory, Nsuserdomainmask, YES)lastobject]stringbyappendingpathcomponent:@ " Student "];
fmdatabasequeue *databaseq = [fmdatabasequeue databasequeuewithpath:p ath];
_databaseq = databaseq;
[_databaseq indatabase: ^ (fmdatabase * _nonnull db) {
BOOL success = [db open];
if(success) {
NSLog(@ " CREATE database Success ");
// Create a table
nsstring *str = @ "CREATE TABLE IF not EXISTS t_student (id INTEGER PRIMARY KEY autoincrement, name TEXT not NU Ll,score REAL not NULL) ";
if([db executeupdate: str]) {
NSLog(@ " CREATE TABLE successfully !") );
}Else{
NSLog(@ " failed to create TABLE !") );
}
}Else{
NSLog(@ " failed to create database ");
}
}];
}
Add Data
-(ibaction) InsertData: (UIButton *) Sender {
[_databaseq indatabase: ^ (fmdatabase * _nonnull db) {
for(int i = 0; i < ; i++) {
nsstring *strname = [nsstring stringwithformat:@ "ming-yuexing-%d", I];
nsstring *sqlstr = [nsstring stringwithformat:@ "INSERT into T_student (name, score) VALUES ( '%@ ',%.2f) ", StrName,arc4random_uniform(+)/10.0];
BOOL success = [db executeupdate: sqlstr];
if(success) {
NSLog(@ " Add success ");
}Else{
NSLog(@ " add failed ");
}
}
}];
}
-(ibaction) Selectdata: (UIButton *) Sender {
[_databaseq indatabase: ^ (fmdatabase * _nonnull db) {
nsstring *sqlstr = @ "SELECT * from T_student WHERE score > 60.0 ORDER by Score DESC";
// Execute query statement
fmresultset *set = [db executeQuery: sqlstr];
while ([set next]) {
nsstring *name = [Set stringforcolumn:@ "name"];
cgfloat score = [Set doubleforcolumn:@ "score"];
NSLog(@ "name =%@ score =%f", Name,score);
}
}];
}
/*
Benefits of using FMDB over SQL :
Thread Safety
when a public resource is used in a , B cannot be modified .
*/
@end
Li Hongqiang iOS Development fmdb thread-safe usage