本人菜鸟,还望大神指正
用之前别忘导入libsqlite3的库还要配置路径哦
#import "DataBaseManager.h"
#import "PersonModel.h"
#define DATABASE_ERROR NSLog(@"%@",_fmdb.lastErrorMessage);
//结合宏定义一般会出现优先级的问题
@interface DataBaseManager()
{
//线程锁 目的:为了避免同一时间,对某条数据进行多次修改
NSLock * _lock;
}
@end
@implementation DataBaseManager
+ (DataBaseManager *)sharedDataBaseManager
{
static DataBaseManager * manager = nil;
@synchronized(self) {
if (manager == nil) {
manager = [[DataBaseManager alloc] init];
}
}
return manager;
}
- (instancetype)init
{
if (self = [super init]) {
//获取沙盒目录
NSHomeDirectory();
//Document 由用户自己生成的文件,2.当手机和电脑连接,通过itunes可以看到此目录文件
//Library 从网络上下载的内容要缓存到此目录下,通过itunes看不到
//tmp 临时目录,变动比较大,不建议放到此目录
_lock = [[NSLock alloc] init];
//由上得到db文件 后缀名为db,或者为sqlite
NSString * dbpath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"ling.db"];
// NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, nsuserdom, );
//路径是数据库db文件的路径
//内部处理:如果该路径下db文件存在,他不会重新创建,反之不存在才会创建
_fmdb = [[FMDatabase alloc] initWithPath:dbpath];
if ([_fmdb open]) {
//如果数据库打开,进行后续的操作
//创建表
NSString * sql = @"create table if not exists stu (sid integer primary key autoincrement,name varchar(256), age integer default 0,image blob)";
BOOL isSuccess = [_fmdb executeUpdate:sql];
if (!isSuccess) {
DATABASE_ERROR
}
}
}
return self;
}
//增加
- (void)insertStudent:(PersonModel *)model
{
//上锁
[_lock lock];
if([_fmdb open])
{
//通过?占位符
//数据类型
//age不能直接传23 需要转换成对象类型 NSNumber
//如果有空数据 应该传NULL
NSString * sql = @"insert into stu (name,age,image) values(?,?,?) ";
BOOL isInsert = [_fmdb executeUpdate:sql,model.name,model.age,model.image];
if (!isInsert) {
DATABASE_ERROR
}
///关闭数据库 避免数据库闲置,减少占用
[_fmdb close];
}
//允许其他人能够进行此操作
[_lock unlock];
}
- (void)deleteStudent
{
if ([_fmdb open]) {
NSString * sql = @"delete from stu where sid = ?";
BOOL isDelete = [_fmdb executeUpdate:sql,[NSNumber numberWithInteger:2]];
if (isDelete) {
DATABASE_ERROR;
}
}
}
//修改更新
- (void)updateStudent
{
if([_fmdb open])
{
NSString * sql = @"update stu set name = ?,age = ?,where sid = ?";
BOOL isupdate = [_fmdb executeUpdate:sql,@"lisi",[NSNumber numberWithInteger:40],[NSNumber numberWithInteger:1]];
if (!isupdate) {
DATABASE_ERROR;
}
}
}
//查看数据
- (NSMutableArray *)selectAllStudent
{
NSMutableArray * array = [[NSMutableArray alloc] init];
if ([_fmdb open]) {
NSString * sql = @"select * from stu";
//注意方法:executeQuery 最终得到查询的结果
FMResultSet * result = [_fmdb executeQuery:sql];
while ([result next]) {
//得到name字段所对应的值
NSString * name = [result stringForColumn:@"name"];
NSNumber * age = [NSNumber numberWithInteger:[result intForColumn:@"age"]];
NSData * image = [result dataForColumn:@"image"];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:name,@"name",age,@"age",image,@"image", nil];
[array addObject:dict];
}
}
return array;
}
@end
权当做个笔记,望大神不要取笑