ITPub博客

首页 > > > FMDB基本使用

FMDB基本使用

作者:unnamed person1 时间:2019-11-29 12:18:39 0 删除 编辑

在工程中导入"FMDB"

#import <FMDatabase.h>

创建一个类

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface DBDCacheTool : NSObject

- (void) set;

@end

#import "DBDCacheTool.h"

#import <FMDatabase.h>

@implementation DBDCacheTool

- (void) set{

}

@end

NS_ASSUME_NONNULL_END

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

对于数据库的操作,体现的代码与写在终端的命令很相似

这里我把增删改查写在一个set方法里用于测试。

文件存放位置

数据库文件放在沙河路径下,每个app有自己的沙盒路径

获取沙盒路径

NSString *docPath = [[NSString alloc] init];

docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSLog(@"docPath == %@", docPath);

1

2

3

创建数据库文件

NSString *fileName =[docPath stringByAppendingPathComponent:@"movie.sqlite"];

FMDatabase *fmdb = [FMDatabase databaseWithPath:fileName];

if ([fmdb open]) {

NSLog(@"数据库打开成功");

} else {

NSLog(@"数据库打开失败");

}

1

2

3

4

5

6

7

创建表并且插入数据,

一行可以有多个数据,这里我只插入了一个name

//创建表

BOOL executeUpdate = [fmdb executeUpdate:@"CREATE TABLE IF NOT EXISTS t_movie (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL);"];

int mark_movie = 1;

NSString *name = [NSString stringWithFormat:@"冰雪奇缘%@",@(mark_movie)];

mark_movie++;

BOOL results = [fmdb executeUpdate:@"INSERT INTO t_movie (name) VALUES (?)",name];

if (results) {

NSLog(@"插入成功");

} else {

NSLog(@"插入失败");

}

1

2

3

4

5

6

7

8

9

10

11

注意此时我们的表的名字是 t_movie;

删除表中数据

这里根据行来删,也就是id

//删除

// BOOL delete = [fmdb executeUpdate:@"delete from t_movie where id = ?",@(1)];

// if (delete) {

// NSLog(@"删除成功");

// } else {

// NSLog(@"删除失败");

// }

1

2

3

4

5

6

7

修改根据名字来修改

// 修改

NSString *newName = @"rushBmMyFriends";

NSString *oldName = @"冰雪奇缘1";

BOOL update = [fmdb executeUpdate:@"update t_movie set name = ? where name = ?",newName, oldName];

if(update) {

NSLog(@"修改成功");

} else {

NSLog(@"修改失败");

}

1

2

3

4

5

6

7

8

9

查询

//查询整个表

FMResultSet * resultSet = [fmdb executeQuery:@"select * from t_movie"];

//按条件查询

//FMResultSet *resultSet = [fmdb executeQuery:@"select * from t_movie where id < ?",@(4)];

//遍历查询

while ([resultSet next]) {

int idNum = [resultSet intForColumn:@"id"];

NSString *name = [resultSet objectForColumn:@"name"];

NSLog(@"姓名:%@ 序号:%d", name, idNum);

}

1

2

3

4

5

6

7

8

9

10

删除表

// // 删除表

// BOOL result = [fmdb executeUpdate:@"drop table if exists t_movie"];

// if (result) {

// NSLog(@"删除成功");

// } else {

// NSLog(@"删除失败");

// }

1

2

3

4

5

6

7

————————————————

版权声明:本文为CSDN博主「wtl1804」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/wtl1804/article/details/103278989

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69949627/viewspace-3156843/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-12-04

  • 博文量
    56
  • 访问量
    0