IOS数据存储

1-iOS中数据存储方式

2-SQLite
3-FMDB


1-iOS中数据存储方式

• Plist(NSArray\NSDictionary) -只能存放系统自带的一些类型
• Preference(偏好设置\NSUserDefaults) –本质上还是plist
• NSCoding(NSKeyedArchiver\NSkeyedUnarchiver)–可以存储自定义类型但是它是一次性读写,不是数据库,性能低
• SQLite3 –可以控制读写,性能高

• Core Data

2-SQLite

数据库存储数据的步骤
• 新建一个数据库文件
• 新建一张表(table)
• 添加多个字段(column,列,属性)
• 添加多行记录(row,每行存放多个字段对应的值)

• SQL语句的特点
• 不区分大小写(比如数据库认为user和UsEr是一样的)
• 每条语句都必须以分号 ; 结尾
• SQL中的常用关键字有
• select、insert、update、delete、from、create、where、desc、order、by、group、table、alter、view、index等等
• 数据库中不可以使用关键字来命名表、字段

主要学习SQLIte的CRUD 即增删改查

DDL:data defination language,主要是产生数据表和删除数据表这些操作

增加一张表
create table if not exists t2 (id integer primary key AUTOINCREMENT,name text not null unique,age integer not null default 1,class_id integer ,constraint fk foreign key (class_id) references t_class(id));

create table if not exists t_student (id integer primary key autoincrement,name text,class_id integer,
constraint fk foreign key (class_id) references t_class(id));

删除一张表
drop table if exists t1;

DML:data manipulation language,包含增、删、修改三种数据库的操作

增加一条记录
insert into t1 values (1,’tom’,21,90);
insert into t1 (name,age,score) values (‘hello’,2,100);

修改某条或某些条记录
update t1 set score = 400 where id == 5;
update t1 set score = 800 where id < 5 and name=’tom’;

删除记录
delete from t1;//删除全部数据
delete from t1 where id >9 and name=’jim’;//删除符合条件的数据

DQL: data query language,包含查询的各种操作

//查询某张表中的全部行和列
select * from t1;
查询表中所有行的两列
select name,age from t1;
查询表中某些行某些列
select name,age from t1 where score >10;
查询有多少条满足条件的记录
select count(*) from t1 where score>10;
查询表中最大的id,同时把该行的列显示出来
select max(id),name,age,score from t1;

查询符合条件的记录,同时按升序排列
select * from t1 where age >2 order by score asc;
select * from t1 where age >2 order by score desc;
先分数排序,分数相同则按年龄排序
select * from t1 where age>2 order by score asc,age desc;

select 一些列 from 表名 where 列的运算 order by 某个列1 asc/desc 某个列2 asc/desc
显示数据表中的前三条记录
select * from t1 limit 3;
跳过前3条记录,显示紧接着的4条记录
select * from t1 limit 3,4;

查询ios1班的全部学生
select * from t_student as s,t_class as c where s.class_id=c.id and c.name=’ios1’;

limit
• 使用limit可以精确地控制查询结果的数量,比如每次只查询10条数据
• 格式
• select * from 表名 limit 数值1, 数值2 ;
• 示例
• select * from t_student limit 4, 8 ;
• 可以理解为:跳过最前面4条语句,然后取8条记录


• limit常用来做分页查询,比如每页固定显示5条数据,那么应该这样取数据
• 第1页:limit 0, 5
• 第2页:limit 5, 5
• 第3页:limit 10, 5
• …
• 第n页:limit 5*(n-1), 5
• 猜猜下面语句的作用
• select * from t_student limit 7 ;
• 相当于select * from t_student limit 0, 7 ;
• 表示取最前面的7条记录

约束
简单约束
• 建表时可以给特定的字段设置一些约束条件,常见的约束有
• not null :规定字段的值不能为null
• unique :规定字段的值必须唯一
• default :指定字段的默认值
(建议:尽量给字段设定严格的约束,以保证数据的规范性)
• 示例
• create table t_student (id integer, name text not null unique, age integer not null default 1) ;
• name字段不能为null,并且唯一
• age字段不能为null,并且默认为1

主键约束
• 如果t_student表中就name和age两个字段,而且有些记录的name和age字段的值都一样时,那么就没法区分这些数据,造成数据库的记录不唯一,这样就不方便管理数据
• 良好的数据库编程规范应该要保证每条记录的唯一性,为此,增加了主键约束
• 也就是说,每张表都必须有一个主键,用来标识记录的唯一性
• 什么是主键
• 主键(Primary Key,简称PK)用来唯一地标识某一条记录
• 例如t_student可以增加一个id字段作为主键,相当于人的身份证
• 主键可以是一个字段或多个字段

主键的声明
• 在创表的时候用primary key声明一个主键
• create table t_student (id integer primary key, name text, age integer) ;
• integer类型的id作为t_student表的主键
• 主键字段
• 只要声明为primary key,就说明是一个主键字段
• 主键字段默认就包含了not null 和 unique 两个约束
• 如果想要让主键自动增长(必须是integer类型),应该增加autoincrement
• create table t_student (id integer primary key autoincrement, name text, age integer) ;

外键约束
• 利用外键约束可以用来建立表与表之间的联系
• 外键的一般情况是:一张表的某个字段,引用着另一张表的主键字段
• 新建一个外键
• create table t_student (id integer primary key autoincrement, name text, age integer, class_id integer, constraint fk_t_student_class_id_t_class_id foreign key (class_id) references t_class (id);
• t_student表中有一个叫做fk_t_student_class_id_t_class_id的外键
• 这个外键的作用是用t_student表中的class_id字段引用t_class表的id字段

表连接查询
• 什么是表连接查询
• 需要联合多张表才能查到想要的数据
• 表连接的类型
• 内连接:inner join 或者 join (显示的是左右表都有完整字段值的记录)
• 左外连接:left outer join (保证左表数据的完整性)
• 示例
• 查询0316iOS班的所有学生
• select s.name,s.age from t_student s, t_class c where s.class_id = c.id and c.name = ‘0316iOS’;

模糊查询
sql语句
select * from XXX where name like ‘%abc%’
select * from t_contact where name like ‘%searchText%’ or phone like ‘%searchText%’
// % 在stringWithFormat中有特殊意思
// %% == %

OC语句
// 输入一个文字,进行模糊查询,查看下名字或者电话是否包含文字
NSString sql = [NSString stringWithFormat:@”select from t_contact where name like ‘%% %@ %%’ or phone like ‘%% %@ %%’;”,searchText,searchText];

3-FMDB

打开数据库

• 通过指定SQLite数据库文件路径来创建FMDatabase对象
FMDatabase *db = [FMDatabase databaseWithPath:path];
if (![db open]) {
NSLog(@”数据库打开失败!”);
}

执行更新
• 在FMDB中,除查询以外的所有操作,都称为“更新”
• create、drop、insert、update、delete等
• 使用executeUpdate:方法执行更新
• - (BOOL)executeUpdate:(NSString*)sql, …
• - (BOOL)executeUpdateWithFormat:(NSString*)format, …
• - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments
• 示例
[db executeUpdate:@”UPDATE t_student SET age = ? WHERE name = ?;”, @20, @”Jack”]

执行查询
• 查询方法
• - (FMResultSet )executeQuery:(NSString)sql, …
• - (FMResultSet )executeQueryWithFormat:(NSString)format, …
• - (FMResultSet )executeQuery:(NSString )sql withArgumentsInArray:(NSArray *)arguments
• 示例
// 查询数据
FMResultSet rs = [db executeQuery:@”SELECT FROM t_student”];
// 遍历结果集
while ([rs next]) {
NSString *name = [rs stringForColumn:@”name”];
int age = [rs intForColumn:@”age”];
double score = [rs doubleForColumn:@”score”];
}

代码片段:一



#import "IWViewController.h"
#import "FMDB.h"

@interface IWViewController ()
@property (nonatomic, strong) FMDatabase *db;
- (IBAction)insert;
- (IBAction)update;
- (IBAction)delete;
- (IBAction)query;
@end

@implementation IWViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 0.获得沙盒中的数据库文件名
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"];

    // 1.创建数据库实例对象
    self.db = [FMDatabase databaseWithPath:filename];

    // 2.打开数据库
    if ( [self.db open] ) {
        NSLog(@"数据库打开成功");

        // 创表
        BOOL result = [self.db executeUpdate:@"create table if not exists t_student (id integer primary key autoincrement, name text, age integer);"];

        if (result) {
            NSLog(@"创表成功");
        } else {
            NSLog(@"创表失败");
        }
    } else {
        NSLog(@"数据库打开失败");
    }
}

- (IBAction)insert
{
    for (int i = 0; i<40; i++) {
        NSString *name = [NSString stringWithFormat:@"rose-%d", arc4random() % 1000];
        NSNumber *age = @(arc4random() % 100 + 1);
        [self.db executeUpdate:@"insert into t_student (name, age) values (?, ?);", name, age];
    }
}

- (IBAction)update
{
    [self.db executeUpdate:@"update t_student set age = ? where name = ?;", @20, @"jack"];
}

- (IBAction)delete
{

}

- (IBAction)query
{
    // 1.查询数据
    FMResultSet *rs = [self.db executeQuery:@"select * from t_student where age > ?;", @50];

    // 2.遍历结果集
    while (rs.next) {
        int ID = [rs intForColumn:@"id"];
        NSString *name = [rs stringForColumn:@"name"];
        int age = [rs intForColumn:@"age"];

        NSLog(@"%d %@ %d", ID, name, age);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值