iOS数据库SQLite的基础知识

什么是数据库?

数据库(Database)是按照数据结构来组织、存储和管理数据的仓库
分为2大种类

  • 关系型数据库(主流)
  • 对象型数据库

SQLite是一款轻型的嵌入式数据库,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它的处理速度比Mysql、PostgreSQL这两款著名的数据库都还快。

数据库存储数据的步骤

数据库的存储结构和excel很像,以表(table)为单位

  1. 新建数据库文件
  2. 新建一张表(table)
  3. 添加多个字段(column,列,属性)
  4. 添加多行记录(row,每行存放多个字段对应的值)
SQLite将数据划分为以下几种存储类型:
  • integer : 整型值
  • real : 浮点值
  • text : 文本字符串
  • blob : 二进制数据(比如文件)

实际上SQLite是无类型的,就算声明为integer类型,还是能存储字符串文本(主键除外),而是为了保持良好的编程规范、方便程序员之间的交流

什么是SQL?

SQL是一种对关系型数据库中的数据进行定义和操作的语言,SQL语言简洁,语法简单

什么是SQL语句?

使用SQL语言编写出来的句子\代码,就是SQL语句。要想操作(增删改查,CRUD)数据库中的数据,必须使用SQL语句

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

SQL语句的种类

  1. 数据定义语句(DDL:Data Definition Language)

    • 包括create和drop等操作
    • 在数据库中创建新表或删除表(create table或 drop table)
  2. 数据操作语句(DML:Data Manipulation Language)

    • 包括insert、update、delete等操作
    • 上面的3种操作分别用于添加、修改、删除表中的数据
  3. 数据查询语句(DQL:Data Query Language)

    • 可以用于查询获得表中的数据
    • 关键字 select 是DQL(也是所有SQL)用得最多的操作
    • 其他DQL常用的关键字有where,order by,group by和having

实际操作

创表
  • 格式
    create table if not exists 表名 (字段名1 字段类型1, 字段名2 字段类型2, …) ;
  • 示例
create table t_student if not exists  (//注意写作格式保持清晰
   id integer, 
   name text, 
   age inetger,
   score real
) ;
删表
  • 格式
    drop table if exists 表名 ;
  • 示例
drop table  if exists t_student ;

插入数据(insert)

  • 格式
    insert into 表名 (字段1, 字段2, …) values (字段1的值, 字段2的值, …) ;
  • 示例
//注意书写格式清晰
insert into t_student
   (name, age)
   values
   (‘lnj’, 10) ;

数据库中的字符串内容应该用单引号 ’ 括住

条件语句

如果只想更新或者删除某些固定的记录,那就必须在DML语句后加上一些条件

  • 条件语句的常见格式
where 字段 = 某个值 ;   // 不能用两个 =
where 字段 is 某个值 ;   // is 相当于 = 
where 字段 != 某个值 ; 
where 字段 is not 某个值 ;   // is not 相当于 != 
where 字段 > 某个值 ; 
where 字段1 = 某个值 and 字段2 > 某个值 ;  // and相当于C语言中的 &&
where 字段1 = 某个值 or 字段2 = 某个值 ;  //  or 相当于C语言中的 ||

更新数据(update)

  • 格式
    update 表名 set 字段1 = 字段1的值, 字段2 = 字段2的值, … ;

  • 示例

update t_student 
  set name = ‘jack’, age = 20 
  where age > 10 and name != ‘jack’  ; 

delete from t_student where age <= 10 or age > 30 ;

删除数据(delete)

  • 格式
    delete from 表名 ;
  • 示例
delete from t_student ;

查询语句

  • 格式
    select 字段1, 字段2, … from 表名 ;
  • 示例
select name, age from t_student ;
select * from t_student where age > 10 ;  //  条件查询

起别名

字段和表都可以起别名,主要用于表连接查询

  • 格式
    select 字段1 别名 , 字段2 别名 , … from 表名 别名 ;
    select 字段1 别名, 字段2 as 别名, … from 表名 as 别名 ;

  • 示例

select name myname, age myage from t_student ;
//给name起个叫做myname的别名,给age起个叫做myage的别名

select s.name, s.age from t_student s ;
//给t_student表起个别名叫做s,利用s来引用表中的字段

表连接查询

需要联合多张表才能查到想要的数据
表连接的类型

  • 内连接:inner join 或者 join (显示的是左右表都有完整字段值的记录)
  • 左外连接:left outer join (保证左表数据的完整性)
select s.name,s.age from t_student s, t_class c where s.class_id = c.id and c.name = ‘0316iOS’;

查询0316iOS班的所有学生(s.class_id = c.id这个是关键

排序

查询出来的结果可以用order by进行排序

  • 格式
    select * from t_student order by 字段 ;
  • 示例
select * from t_student order by age desc ;  //降序
select * from t_student order by age asc ;   // 升序(默认)
select * from t_student order by age asc, height desc ;

计算记录的数量

  • 格式
    select count (字段) from 表名 ;
    select count ( * ) from 表名 ;
  • 示例
select count (age) from t_student ;
select count ( * ) from t_student where score >= 60;

limit

使用limit可以精确地控制查询结果的数量

  • 格式
    select * from 表名 limit 数值1, 数值2 ;
  • 示例
select * from t_student limit 4, 8 ;//跳过最前面4条语句,然后取8条记录
简单约束

建表时可以给特定的字段设置一些约束条件
(建议:尽量给字段设定严格的约束,以保证数据的规范性)
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声明

  • 主键可以是一个字段或多个字段

  • 主键字段默认就包含了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字段

使用之前首先在lib库中导入 libsqlite3.0dylib 文件

#import "HMViewController.h"
#import <sqlite3.h>
#import "HMShop.h"

@interface HMViewController () <UITableViewDataSource, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *priceField;
/** 数据库对象实例 */
@property (nonatomic, assign) sqlite3 *db;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)insert;
@property (nonatomic, strong) NSMutableArray *shops;
@end

@implementation HMViewController

- (NSMutableArray *)shops
{
    if (!_shops) {
        self.shops = [[NSMutableArray alloc] init];
    }
    return _shops;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 增加搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.frame = CGRectMake(0, 0, 320, 44);
    searchBar.delegate = self;
    self.tableView.tableHeaderView = searchBar;
    
    // 初始化数据库
    [self setupDb];
    
    // 查询数据
    [self setupData];
    
    // 关闭数据库
    //    sqlite3_close();
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.shops removeAllObjects];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT name,price FROM t_shop WHERE name LIKE '%%%@%%' OR  price LIKE '%%%@%%' ;", searchText, searchText];
    // stmt是用来取出查询结果的
    sqlite3_stmt *stmt = NULL;
    // 准备
    int status = sqlite3_prepare_v2(self.db, sql.UTF8String, -1, &stmt, NULL);
    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
        while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
            const char *name = (const char *)sqlite3_column_text(stmt, 0);
            const char *price = (const char *)sqlite3_column_text(stmt, 1);
            
            HMShop *shop = [[HMShop alloc] init];
            shop.name = [NSString stringWithUTF8String:name];
            shop.price = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
        }
    }
    
    [self.tableView reloadData];
}

/**
 查询数据
 */
- (void)setupData
{
    const char *sql = "SELECT name,price FROM t_shop;";
    // stmt是用来取出查询结果的
    sqlite3_stmt *stmt = NULL;
    // 准备
    int status = sqlite3_prepare_v2(self.db, sql, -1, &stmt, NULL);
    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
        while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
            const char *name = (const char *)sqlite3_column_text(stmt, 0);
            const char *price = (const char *)sqlite3_column_text(stmt, 1);
            
            HMShop *shop = [[HMShop alloc] init];
            shop.name = [NSString stringWithUTF8String:name];
            shop.price = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
        }
    }
}

/**
 初始化数据库
 */
- (void)setupDb
{
    // 打开数据库(连接数据库)
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
    // 如果数据库文件不存在, 系统会自动创建文件自动初始化数据库
    int status = sqlite3_open(filename.UTF8String, &_db);
    if (status == SQLITE_OK) { // 打开成功
        NSLog(@"打开数据库成功");
        
        // 创表
        const char *sql = "CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);";
        char *errmsg = NULL;
        sqlite3_exec(self.db, sql, NULL, NULL, &errmsg);
        if (errmsg) {
            NSLog(@"创表失败--%s", errmsg);
        }
    } else { // 打开失败
        NSLog(@"打开数据库失败");
    }
}

- (IBAction)insert {
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_shop(name, price) VALUES ('%@', %f);", self.nameField.text, self.priceField.text.doubleValue];
    sqlite3_exec(self.db, sql.UTF8String, NULL, NULL, NULL);
    
    // 刷新表格
    HMShop *shop = [[HMShop alloc] init];
    shop.name = self.nameField.text;
    shop.price = self.priceField.text;
    [self.shops addObject:shop];
    [self.tableView reloadData];
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shops.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"shop";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        cell.backgroundColor = [UIColor grayColor];
    }
    
    HMShop *shop = self.shops[indexPath.row];
    cell.textLabel.text = shop.name;
    cell.detailTextLabel.text = shop.price;
    
    return cell;
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,753评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,668评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,090评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,010评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,054评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,806评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,484评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,380评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,873评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,021评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,158评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,838评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,499评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,044评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,159评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,449评论 3 374
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,136评论 2 356

推荐阅读更多精彩内容