美文网首页数据储存
iOS 数据存储(六) -持久化 sqlite

iOS 数据存储(六) -持久化 sqlite

作者: 搬砖的crystal | 来源:发表于2022-07-26 15:56 被阅读0次

一、简介

SQLite 是轻量型关系型数据库;占用资源非常少;是无类型的数据库(意思是可以保存所有类型的数据)。

优点

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

二、使用

1.首先要添加库文件 libsqlite3.tbd
2.使用
#import "ViewController.h"
#import <sqlite3.h>
@interface ViewController ()
@property (nonatomic,assign) sqlite3 *database;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createDataBase];
    [self createForm];
    [self insertData:@"xiaowang" ageinteger:10 sexStr:@"male"];
    [self sqlData];
}

//生成路径
-(NSString *)path{
    
    NSArray *documentArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentPath = [documentArr firstObject];
    // crylown.db 为数据库的名字
    NSString *path = [NSString stringWithFormat:@"%@/student.sqlite",documentPath];
    NSLog(@"位置path == %@",path);
    return path;
}

//创建/打开数据库
-(void)createDataBase{

    int databaseResult = sqlite3_open([[self path] UTF8String], &_database);
    if (databaseResult == SQLITE_OK) {
          [self createForm];
    }else{
          NSLog(@"创建/打开数据库失败,%d",databaseResult);
    }
}

//创建表
-(void)createForm{
   
     char *error = NULL;
    //    建表格式: create table if not exists 表名 (列名 类型,....)    注: 如需生成默认增加的id: id integer primary key autoincrement
    const char *createSQL = "create table if not exists t_students (id integer primary key autoincrement, name text, age integer, sex text)";
    // 执行sql语句
    /**
       第1个参数:数据库对象
       第2个参数:sql语句
       第3个参数:查询时候用到的一个结果集闭包
       第4个参数:用不到
       第5个参数:错误信息
     */
    int tableResult = sqlite3_exec(_database, createSQL, NULL, NULL, &error);
    
    if (tableResult == SQLITE_OK) {
        NSLog(@"创建成功");
    }else{
        NSLog(@"创建表失败:%s",error);
    }
}

// 插入数据
- (void)insertData:(NSString*)name ageinteger:(int)age sexStr:(NSString*)sex{
    // 拼接 sql 语句
    NSString *sql = [NSString stringWithFormat:@"insert into t_students (name,age,sex) values ('%@',%d,'%@');",name,age,sex];
    // 执行 sql 语句
    char *errMsg = NULL;
    int result = sqlite3_exec(_database, sql.UTF8String, NULL, NULL, &errMsg);
    
    if (result == SQLITE_OK) {
        NSLog(@"插入数据成功 - %@",name);
    } else {
        NSLog(@"插入数据失败 - %s",errMsg);
    }
}

// 查询操作
- (void)sqlData {
    // sql语句
    const char *sql="SELECT id,name,age,sex FROM t_students WHERE age<20;";
    sqlite3_stmt *stmt = NULL;
    /**
         第1个参数:一个已经打开的数据库对象
         第2个参数:sql语句
         第3个参数:参数2中取出多少字节的长度,-1 自动计算,\0停止取出
         第4个参数:准备语句
         第5个参数:通过参数3,取出参数2的长度字节之后,剩下的字符串
       */
    // 进行查询前的准备工作
    if (sqlite3_prepare_v2(_database, sql, -1, &stmt, NULL) == SQLITE_OK) {   // sql语句没有问题
        NSLog(@"sql语句没有问题");
        
        // 每调用一次sqlite3_step函数,stmt就会指向下一条记录
        while (sqlite3_step(stmt) == SQLITE_ROW) {  // 找到一条记录
            // 取出数据
            int ID = sqlite3_column_int(stmt, 0);   // 取出第0列字段的值
            const unsigned char *name = sqlite3_column_text(stmt, 1);   // 取出第1列字段的值
            int age = sqlite3_column_int(stmt, 2);  // 取出第2列字段的值
            const unsigned char *sex = sqlite3_column_text(stmt, 3);
            printf("%d %s %d\n %s",ID,name,age,sex);
        }
    } else {
        NSLog(@"查询语句有问题");
    }
}

//修改数据
-(void)updateData{
    
    //其实Sqlite的数据插入,修改,删除执行的方法都是一样的只是执行的sql语句不一样,想知道sql的更多语句操作自行百度了,比较多这里就不讲解了,只介绍一些基本的操作方法。
    //sqlite3数据(把年龄大于60的学生名字全部改成‘哈哈’)
    NSString *sql = @"update t_students set name = '哈哈' where age > 60";
    char *errorMesg = NULL;
    int result = sqlite3_exec(_database, sql.UTF8String, NULL, NULL, &errorMesg);
    if (result == SQLITE_OK) {

            NSLog(@"更改成功");
        }else {

            NSLog(@"更改失败");
        }
    //然后执行查询语句就能看到更改后的效果了
}

//删除数据
-(void)deleteData{
    //删除表中年龄大于60的学生数据
    NSString *sql = @"delete from t_students where age >= 60";
    char *errorMesg = NULL;
    int result = sqlite3_exec(_database, sql.UTF8String, NULL, NULL, &errorMesg);
    if (result == SQLITE_OK) {

        NSLog(@"删除成功");
    }else {

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

@end

三、FMDB

实际工作中一般使用第三方库 FMDB。FMDB 是将 sqlite 封装处理的,所以使用 FMDB 之前也必须导入 libsqlite3.dylib 框架。

相关文章

  • SQLite数据库

    在学习SQLite之前,首先了解下数据持久化的几种方式: 定义:数据持久化是通过文件将数据存储在磁盘上 IOS下主...

  • iOS 数据存储(六) -持久化 sqlite

    一、简介 SQLite 是轻量型关系型数据库;占用资源非常少;是无类型的数据库(意思是可以保存所有类型的数据)。 ...

  • swift 之归档和解归档

    数据持久化的方式有很多种,归档是其中的一种,说起数据持久化的方式,iOS 中基本有以下几种方式:sqlite存储、...

  • iOS-数据持久化之--SQLite3

    四种数据持久化方式总目录 3.SQLite3 iOS的嵌入式SQL数据库,名为SQLite3。SQLite3在存储...

  • 【iOS】数据持久化方案

    iOS中主要有5种常见的数据持久化方式:NSUserDefault、属性列表文件存储、归档、SQLite、Core...

  • iOS数据持久化

    Title: iOS数据持久化 ##数据持久化概念 数据持久化就是将内存中的数据模型转换为存储模型,以及将存储模型...

  • 《第一行代码:Android》读书笔记——第6章 数据持久化

    本文主要讲述了Android数据持久化的三种方式:文件存储、SharedPreference存储、SQLite数据...

  • iOS数据存储

    iOS数据存储 持久化存储 概述: 持久化存储——将数据保存在硬盘里,当应用程序重启后可以访问到之前存储的数据。是...

  • 数据持久化机制

    iOS中数据持久化的几种方式:1.属性列表2.对象归档3.数据库存储(SQLite3)4.苹果公司提供的持久性工具...

  • iOS开发 - 关于 CoreData 的使用

    简介: CoreData 是数据持久化存储的最佳方式. CoreData 是基于 sqlite 的封装, 数据保存...

网友评论

    本文标题:iOS 数据存储(六) -持久化 sqlite

    本文链接:https://www.haomeiwen.com/subject/xdvoirtx.html