/**
* 创建表
*/
- (void)createTable
{
//1.初始化数据库对象 并且 2.打开数据库
BOOL isOpenSuccess = [self.database open];
NSLog(@"数据库打开%@",isOpenSuccess?@"成功":@"失败");
//3.创建表
NSString *sql = @"create table if not exists User (id integer primary key autoincrement, name text, age integer, icon blob)";
//执行sql,除了查询外,其他的操作都是更新
BOOL isCreateTableOK = [self.database executeUpdate:sql];
NSLog(@"创建表%@",isCreateTableOK?@"成功":@"失败");
}
//初始化数据库对象
- (FMDatabase *)database
{
if (!_database)
{
_database = [FMDatabase databaseWithPath:[self databasePath]];
}
return _database;
}
/**
* 返回数据库路径
*
* @return return value description
*/
- (NSString *)databasePath
{
//获取document路径
NSString *docuentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
return [docuentPath stringByAppendingPathComponent:@"user.db"];
}
/**
* 插入指定数据
*
* @param user user description
*
* @return return value description
*/
- (BOOL)insertUserObjectWithUser:(User *)user
{
NSString *sql = @"insert into User (name,age,icon) values (?,?,?)";
//执行插入的sql语句
BOOL isInsertOK = [self.database executeUpdate:sql,user.name,@(user.age),user.iconData];
NSLog(@"插入数据%@",isInsertOK?@"成功":@"失败");
return YES;
}
/**
* 更新数据
*
* @param user user description
*
* @return return value description
*/
- (BOOL)updateUserObjectWithUser:(User *)user
{
NSString *sql = [NSString stringWithFormat:@"update user set name='%@',age='%d',icon='%@' where name = '%@'",user.name,user.age,user.iconData,user.name];
BOOL isInsertOK = [self.database executeUpdate:sql];
NSLog(@"==========更新数据%@===========",isInsertOK?@"成功":@"失败");
return YES;
}
/**
* 查询所有的数据
*
* @return return value description
*/
- (NSArray *)queryAllUserObjectsFromDatabase
{
//保存所有的用户信息
NSMutableArray *users = [NSMutableArray array];
NSString *sql = @"select * from User";
//执行查询
FMResultSet *result = [self.database executeQuery:sql];
//遍历
while (result.next)
{
User *user = [[User alloc] init];
//取值
//根据字段名字取值
user.iconData = [result dataForColumn:@"icon"];
user.name = [result stringForColumn:@"name"];
user.age = [result intForColumn:@"age"];
[users addObject:user];
}
return users;
}