当前位置:Gxlcms > 数据库问题 > FMDB基本应用

FMDB基本应用

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

1.打开数据库

  1. #import "ViewController.h"
  2. #import "FMDB.h"
  3. @interface ViewController ()
  4. @property (nonatomic, strong) FMDatabase *db;
  5. @end
  6. @implementation ViewController
  7. - (void)viewDidLoad {
  8. [super viewDidLoad];
  9. //打开数据库
  10. [self dbOpen];
  11. }
  12. /**
  13. * 打开数据库
  14. */
  15. -(void)dbOpen
  16. {
  17. //1.获取数据库文件的路径
  18. NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  19. NSString *fileName=[doc stringByAppendingPathComponent:@"toothGroup.sqlite"];
  20. NSLog(@"%@",fileName);
  21. //2.获得数据库
  22. FMDatabase *db=[FMDatabase databaseWithPath:fileName];
  23. //3.打开数据库
  24. if ([db open]) {
  25. //创建表的时候必须要有一个integer类型的,否则创建不成功
  26. NSString *create=@"create table if not exists t_group11(id integer primary key autoincrement,filename text NOT NULL,title text NOT NULL,price text NOT NULL,endTime text NOT NULL)";
  27. BOOL result=[db executeUpdate:create];
  28. if (result) {
  29. NSLog(@"创表成功");
  30. }
  31. else
  32. {
  33. NSLog(@"创表失败");
  34. }
  35. }
  36. self.db=db;
  37. }

 

2.插入数据

  1. //往数据库插入数据 缓存数据
  2. if ([self.db open]) {
  3. NSString *sql=[NSString stringWithFormat: @"INSERT INTO t_group11 (filename,title,price,endTime) VALUES(‘%@‘,‘%@‘,‘%@‘,‘%@‘)",dict[@"filename"],dict[@"title"],dict[@"price"],dict[@"endTime"]];
  4. BOOL result=[self.db executeUpdate:sql];
  5. if (result) {
  6. NSLog(@"插入成功");
  7. }
  8. else
  9. {
  10. NSLog(@"插入失败");
  11. }
  12. }

 

 

3.查询数据

  1. // 1.执行查询语句
  2. FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM t_group11"];
  3. // 2.遍历结果
  4. while ([resultSet next]) {
  5. int ID = [resultSet intForColumn:@"id"];
  6. NSString *filename=[resultSet stringForColumn:@"filename"];
  7. NSString *title=[resultSet stringForColumn:@"title"];
  8. NSString *price=[resultSet stringForColumn:@"price"];
  9. NSString *endTime=[resultSet stringForColumn:@"endTime"];
  10. NSLog(@"%d %@ %@ %@ %@", ID, filename, title,price,endTime);
  11. }

 

4.删除数据

  1. //删除表
  2. [self.db executeUpdate:@"DROP TABLE IF EXISTS t_group11"];

 

 

 

 

   

FMDB基本应用

标签:

人气教程排行