当前位置:Gxlcms > 数据库问题 > FMDB的简单使用

FMDB的简单使用

时间:2021-07-01 10:21:17 帮助过:2人阅读

"RootViewController.h" #import "FMDatabase.h" @interface RootViewController () { FMDatabase * myDB; } @end @implementation RootViewController //FMDB是将SQLite中复杂的SQL语法进行封装 //FMDB适用于ARC或者MRC环境的编码 //具有完美的添加、查找、删除、修改数据库的方法 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (IBAction)createDB:(id)sender { //数据库在使用之前 一定要确保在沙盒路径下确实存在该库 //<1>获取当前工程沙盒路径 //数据库的后缀是.db或者.sqlite NSString * path = [NSHomeDirectory() stringByAppendingString:@"/Documents/person.db"]; //使用数据库 必须确保这个数据库是打开状态 //<2>打开数据库 myDB = [[FMDatabase alloc]initWithPath:path]; BOOL isOpen = [myDB open]; if(isOpen) { NSLog(@"数据库打开成功"); } else { NSLog(@"数据库打开失败%@",[myDB lastErrorMessage]); } //如果在该路径下存在person.db这个库 就直接打开该库 如果不存在这个库 就先创建库再打开 //不会在同一个路径下创建同名的库 //创建表格 NSString * sql = @"create table if not exists Users(ID integer primary key autoincrement,name varchar(256),age integer,headImage blob)"; //blob表示的是二进制 BOOL isSuccess = [myDB executeUpdate:sql]; //executeUpdate:除了查询语句 剩余的其他语句都是用该方法调用 if(isSuccess) { NSLog(@"表格创建成功"); } else { NSLog(@"表格创建失败%@",myDB.lastErrorMessage); } //表格与数据库是一样的 在同一个路径下创建同名表格失败 NSLog(@"%@",path); } - (IBAction)insertDB:(id)sender { NSString * sql = @"insert into Users(name,age,headImage) values (?,?,?)"; //? 占位符 可以是任意类型的对象指针 不能是基本类型的数据 如果想要存放基本类型的数据 需要将基本类型的数据封装成OC的对象 NSString * nameStr = @"张三"; NSNumber * ageNum = [NSNumber numberWithInt:20]; UIImage * image = [UIImage imageNamed:@"0.png"]; //图片需要转化成NSData类型 NSData * data = UIImagePNGRepresentation(image); //拼接sql语句 BOOL ret = [myDB executeUpdate:sql,nameStr,ageNum,data]; if(ret) { NSLog(@"数据添加成功"); } else { NSLog(@"数据添加失败%@",myDB.lastErrorMessage); } } - (IBAction)updateDB:(id)sender { NSString * sql = @"update Users set age = ? where name = ?"; NSString * name = @"张三"; NSNumber * ageNum = [NSNumber numberWithInt:50]; BOOL ret = [myDB executeUpdate:sql,ageNum,name]; if(ret) { NSLog(@"修改成功"); } else { NSLog(@"修改失败%@",myDB.lastErrorMessage); } } - (IBAction)selectDB:(id)sender { NSString * sql = @"select * from Users where name = ?"; NSString * name = @"张三"; FMResultSet * result = [myDB executeQuery:sql,name]; while ([result next]) { NSString * name = [result stringForColumn:@"name"]; //stringForColumn:会将该列的数据读出 以字符串的形式获取 int age = [result intForColumnIndex:2]; //按钮列的下标读取数据 读出的数据直接转化成int类型 NSData * imageData = [result dataForColumn:@"headImage"]; UIImage * headImage = [UIImage imageWithData:imageData]; self.nameLabel.text = name; self.ageLabel.text = [NSString stringWithFormat:@"%d",age]; self.headImage.image = headImage; } } - (IBAction)deleteDB:(id)sender { NSString * sql = @"delete from Users where name = ?"; NSString * name = @"张三"; BOOL ret = [myDB executeUpdate:sql,name]; if(ret) { NSLog(@"删除成功"); } else { NSLog(@"删除失败"); } } - (IBAction)closeDB:(id)sender { //数据库关闭了以后 就不能对数据库进行其他操作 if(myDB) { [myDB close]; myDB = nil; } }

 

FMDB的简单使用

标签:

人气教程排行