IOS开发-UI学习-sqlite数据库的操作

IOS开发-UI学习-sqlite数据库的操作

  sqlite是一个轻量级的数据库,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了,而且它的处理速度比Mysql、PostgreSQL这两款著名的数据库都还快,在ios和安卓app中常用来完成对数据进行离线缓存的处理,如新闻数据的离线缓存。

它的基本操作步骤是:

1、先加入sqlite开发库libsqlite3.dylib,

2、新建或打开数据库,

3、创建数据表,

4、插入数据,

5、查询数据并打印,

6、关闭数据库,

具体操作步骤如下:

1、导入sqlite数据库所需头文件:

导入完成后如图所示:

2、程序代码的编制:

 1 //
 2 //  ViewController.m
 3 //  sqlite手动创建数据库和表
 4 //
 5 //  Created by mac on 16/4/12.
 6 //  Copyright © 2016年 mzw. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 #import "FMDatabase.h"
11 @interface ViewController (){
12     FMDatabase *mydb;
13     NSString * idd;
14     NSString * age;
15     NSString * name;
16 }
17 
18 @end
19 
20 @implementation ViewController
21 
22 - (void)viewDidLoad {
23     [super viewDidLoad];
24     
25     
26 //    创建一个数据库路径path
27     NSString *path =[NSHomeDirectory() stringByAppendingString:@"/Documents/mydb.sqlite"];
28     
29 //    根据创建好的路径path生成数据库
30     mydb = [[FMDatabase alloc]initWithPath:path];
31     
32 //    创建一个在数据库中创建表mytable的字符串
33     NSString *tablecreate = @"create table if not exists mytable(id txt primary key,name text,age text)";
34     
35 //    打开数据库
36     if ([mydb open]) {
37         
38 //        使用创建好的字符串新建表mytable
39         BOOL createOK = [mydb executeUpdate:tablecreate];
40         
41     
42         if (createOK) {
43 //            如果创建成果,打印创建成功的提示
44             NSLog(@"数据库创建成功");
45             
46 //            使用sql语句中的insert into语句往创建好的mytable中添加一条记录
47             BOOL insertOK = [mydb executeUpdate:@"insert into mytable(id,age,name) values(?,?,?)",@"1",@"23",@"huangweiqiang"];
48             
49 //            使用sql语句中的insert into语句往创建好的mytable中添加多条记录
50             BOOL insertsOK = [mydb executeUpdate:@"insert into mytable(id,age,name) select '2','24','mazhongwei' union all select '3','21','xiangyiyao' union all select '4','34','zhanglong'"];
51             
52 //             使用sql语句中的delete from语句删除符合条件的语句
53             [mydb executeUpdate:@"delete from mytable where id = '4'"];
54             
55 //             使用sql语句中的update更新表中的记录
56             [mydb executeUpdate:@"update mytable set age = '100000' where id = '3'"];
57             
58 //              使用sql语句中的查询语句查询符合条件的语句,返回结果为一个集合,使用next函数遍历结果并赋值给idd,age,name三个变量
59             FMResultSet *rsset = [mydb executeQuery:@"select * from mytable where id = '3'"];
60             while ([rsset next]) {
61                 idd  = [rsset stringForColumn:@"id"];
62                 age  = [rsset stringForColumn:@"age"];
63                 name = [rsset stringForColumn:@"name"];
64             }
65             
66 //           操作完成后关闭数据库
67             [mydb close];
68             
69 //            打印查询结果
70             NSLog(@"%@_%@_%@",idd,age,name);
71          
72         }else{
73 //            如果创建失败,返回失败提示
74             NSLog(@"数据库创建失败");
75         }
76     }
77     
78 }
79 
80 
81 
82 @end
原文地址:https://www.cnblogs.com/jiwangbujiu/p/5382144.html