zoukankan      html  css  js  c++  java
  • 数据库SQLite(3)

    上一篇介绍了coreData的简单使用,这一次是对SQLite的使用。这两者的不同之处就是SQLite需要添加数据库编写语句,很麻烦。

    一、步骤

    使用SQLite数据库步骤如下:

    1. 打开数据库(如果没有数据库会自动创建自己定义的数据库)
    2. 创建表格
    3. 执行SQL语句
    4. 实现功能

    二、代码实现

     1 //定义静态变量  static sqlite3 *_sql; 

     1 //1.打开数据库
     2     //1.1 获取沙盒中数据库文件的文件路径
     3     NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/sql.db"];
     4     NSLog(@"%@",filePath);
     5     //1.2 执行打开(创建)数据库的方法 (如果目录下没有数据库文件 会自动创建)
     6     /*
     7      1.打开数据库
     8      int sqlite3_open(
     9      const char *filename,   // 数据库的文件路径
    10      sqlite3 **ppDb          // 数据库实例
    11      );
    12      */
    13     int result = sqlite3_open([filePath UTF8String], &_sql);
    14     //判断是否存在,存在就打开,而不是重新创建
    15     //result:int 类型 执行打开(创建)数据库的方法返回的参数
    16     //SQLITE_OK = 0 枚举类型 创建/打开数据库方法(SQL语句)执行的状态
    17     if (result == SQLITE_OK) {
    18         NSLog(@"打开数据库成功!");
    19         //2.建立表格
    20         //初始化SQL语句
    21         const char *sql = " create table if not exists t_student (id integer primary key autoincrement, name text, age integer, score real); ";
    22         //传入执行错误的参数
    23         char *error = NULL;
    24         //执行创建表格的方法
    25     /*
    26      2.执行任何SQL语句
    27      int sqlite3_exec(
    28      sqlite3*,                                  // 一个打开的数据库实例
    29      const char *sql,                           // 需要执行的SQL语句
    30      int (*callback)(void*,int,char**,char**),  // SQL语句执行完毕后的回调
    31      void *,                                    // 回调函数的第1个参数
    32      char **errmsg                              // 错误信息
    33      );
    34      */
    35         int result = sqlite3_exec(_sql, sql, NULL, NULL, &error);
    36         if (result == SQLITE_OK) {
    37             NSLog(@"创建表格成功!");
    38         }else {
    39             NSLog(@"创建表格失败!");
    40         }
    41     }else {
    42         NSLog(@"打开数据库失败!");
    43     }

     当执行完毕这一句代码的时候就会创建出数据库--int result = sqlite3_open([filePath UTF8String], &_sql);读者应该注意注释部分的解释,很重要,在这里不一一赘述。

    复制地址,找到文件并打开文件(使用Navicat Premium软件)

    三、添加数据。

    在数据库中循环写入了5条数据。

     1 //添加数据
     2 - (IBAction)insert {
     3     int i;
     4     for (i = 1; i <= 5; i ++) {
     5         int index = i;
     6         NSString *name = [NSString stringWithFormat:@"小明%d",index];
     7         //年龄、分数设置为随机
     8         int age = arc4random()%100;
     9         float score = arc4random()%100;
    10         //SQL语句
    11         NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age, score) values ('%@', %d, %.2f);
    ",name, age, score];
    12         char *error = NULL;
    13         //
    14         int result = sqlite3_exec(_sql, [sql UTF8String], NULL, NULL, &error);
    15         if (result == SQLITE_OK) {
    16             NSLog(@"添加数据成功!");
    17         }else {
    18             NSLog(@"添加数据失败!");
    19         }
    20     }
    21     i = 1;
    22 }

    四、删除数据

    从数据库中删除数据,可以全部删除,也可以有选择行的删除。

     1   //删除全部数据
     2 //    NSString *sql = [NSString stringWithFormat:@"delete from t_student;"];
     3     //删除选择的数据,需要清楚的知道选择的数据
     4     NSString *sql = [NSString stringWithFormat:@"delete from t_student where name = '小明3'; "];
     5     char *error = NULL;
     6     int result = sqlite3_exec(_sql, [sql UTF8String], NULL, NULL, &error);
     7     if (result == SQLITE_OK) {
     8         NSLog(@"删除数据成功!");
     9     }else {
    10         NSLog(@"删除数据失败!");
    11     }
    12 }

     五、更新数据(修改)

     1 //更新数据
     2 - (IBAction)upData {
     3     NSString *sql = [NSString stringWithFormat:@"update t_student set name = '小虎' where name = '小明1' "];
     4     char *error = NULL;
     5     //执行SQL语句
     6     int result = sqlite3_exec(_sql, [sql UTF8String], NULL, NULL, &error);
     7     if (result == SQLITE_OK) {
     8         NSLog(@"更新数据成功!");
     9     }else {
    10         NSLog(@"更新数据失败!");
    11     }
    12 }

    六、查询数据

    其实,思考一下,无论是修改、删除都需要查询数据。

     1 //查询数据
     2 - (IBAction)query {
     3     //使用占位符 stmt,
     4     NSString *sql = [NSString stringWithFormat:@" select * from t_student where name = ?; "];
     5     //2.定义一个存放集
     6     sqlite3_stmt *stmt = nil;
     7     //错误查询
     8     const char *error = NULL;
     9     //3.检测SQL语句的合法性,并将stmt 和 我们构造的sql语句进行了绑定,通过stmt可以填充SQL语句
    10     //验证sql语句是否正确
    11     /**
    12      *参数1:数据库指针,
    13      *参数2:sql语句
    14      *参数3:sql语句的长度写成-1,自动计算sql语句的最大长度,否则要自己计算长度
    15      *参数4:sql语句的管理指针
    16      *参数5:预留参数,未来使用
    17      */
    18     int result = sqlite3_prepare_v2(_sql, [sql UTF8String], -1, &stmt, &error);
    19     if (result == SQLITE_OK) {
    20         //参数1:sql语句管理指针
    21         //参数2:上面sql语句中 ?的位置,?的下标从1开始
    22         //参数3:要绑定的数据
    23         //参数4:数据的长度
    24         sqlite3_bind_text(stmt, 1, "小明4", -1, NULL);
    25 //        //绑定字段
    26 //        sqlite3_bind_int(stmt, 2, 22);
    27 //        sqlite3_bind_int(stmt, 3, 98);
    28         //执行SQL语句
    29         int result = sqlite3_step(stmt);
    30         
    31         if (result == SQLITE_ROW) {//如果查询到某一行数据,就会返回SQLITE_ROW
    32            int age = sqlite3_column_int(stmt, 2);
    33            NSLog(@"查询成功");
    34            NSLog(@"%d",age);
    35         }
    36     }
    37 }

      1. 检测SQL语句的合法性,并将stmt 和 我们构造的sql语句进行了绑定,通过stmt可以填充SQL语句

              sqlite3_prepare_v2(<#sqlite3 *db#>, <#const char *zSql#>, <#int nByte#>, <#sqlite3_stmt **ppStmt#>, <#const char **pzTail#>)

        2. 执行SQL语句

        sqlite3_exec(<#sqlite3 *#>, <#const char *sql#>, <#int (*callback)(void *, int, char **, char **)#>, <#void *#>, <#char **errmsg#>)

      3. 绑定字段  

             sqlite3_bind_int(<#sqlite3_stmt *#>, <#int#>, <#int#>)

             sqlite3_bind_text(<#sqlite3_stmt *#>, <#int#>, <#const char *#>, <#int n#>, <#void (*)(void *)#>)

             sqlite3_bind_double(<#sqlite3_stmt *#>, <#int#>, <#double#>)

    效果图如下:

    当使用完数据库之后,要关闭数据库。这里没有关闭。

    文章是作者原著,如若转载,请标明出处。欢迎各位来喷。 

  • 相关阅读:
    贪心法之活动安排问题
    动态规划算法之最优二叉搜索树
    动态规划之最大字段和问题
    动态规划算法之图像压缩问题
    动态规划算法之0-1背包问题
    动态规划算法之投资问题
    平面点集的凸包问题
    动态规划(DP)之多边形游戏问题
    凸多边形最优三角划分
    最长公共子序列问题
  • 原文地址:https://www.cnblogs.com/david-han/p/4882161.html
Copyright © 2011-2022 走看看