iOS之Sqlite3编程

一、SQL语法

SQLite将数据划分为以下几种存储类型:

integer : 整型值
real : 浮点值
text : 文本字符串
blob : 二进制数据(比如文件)

实际上SQLite是无类型的
就算声明为integer类型,还是能存储字符串文本(主键除外)
建表时声明啥类型或者不声明类型都可以,也就意味着创表语句可以这么写:
create table t_student(name, age);

为了保持良好的编程规范、方便程序员之间的交流,编写建表语句的时候最好加上每个字段的具体类型

数据库定义语句(DDL:data difinition language)

包括create和drop等操作
在数据库中创建新表或删除表(create table或 drop table)

语法如下:
create table 表名 (字段名1 字段类型1, 字段名2 字段类型2, …) ;
create table if not exists 表名 (字段名1 字段类型1, 字段名2 字段类型2, …) ;
drop table 表名 ;
drop table if exists 表名 ;

语句实例如下:
create table if not exists t_student (id integer primary key autoincrement, name text not null, age default 6);
drop table if exists t_student;

数据操作语句(DML:Data Manipulation Language)

包括insert、update、delete等操作
上面的3种操作分别用于添加、修改、删除表中的数据

语法如下:
insert into 表名 (字段1, 字段2, …) values (字段1的值, 字段2的值, …) ;
update 表名 set 字段1 = 字段1的值, 字段2 = 字段2的值, … ;
delete from 表名 ;

语句实例如下:
insert into t_student (id, name, age) values (1, ‘张三’, 10);
update t_student set name = ‘李四’, age = 11;
delete from t_student where id = 1;

数据查询语句(DQL:Data Query Language)

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

语法如下:
select 字段1, 字段2, … from 表名 ;
select * from 表名; // 查询所有的字段

语句实例如下:
select * from t_student;
select name from t_student where id = 1;

条件语句

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

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

起别名

格式(字段和表都可以起别名)
select 字段1 别名 , 字段2 别名 , … from 表名 别名 ;
select 字段1 别名, 字段2 as 别名, … from 表名 as 别名 ;
select 别名.字段1, 别名.字段2, … from 表名 别名 ;

示例
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来引用表中的字段

计算记录的数量

格式
select count (字段) from 表名 ;
select count ( * ) from 表名 ;

示例
select count (age) from t_student ;
select count ( * ) from t_student where score >= 60;

排序

查询出来的结果可以用order by进行排序
select * from t_student order by 字段 ;
select * from t_student order by age ;

默认是按照升序排序(由小到大),也可以变为降序(由大到小)
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 ;
先按照年龄排序(升序),年龄相等就按照身高排序(降序)

分页

使用limit可以精确地控制查询结果的数量,比如每次只查询10条数据

格式
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,简称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) (id)) ; references t_class
t_student表中有一个叫做fk_t_student_class_id_t_class_id的外键
这个外键的作用是用t_student表中的class_id字段引用t_class表的id字段

表连接查询

什么是表连接查询
需要联合多张表才能查到想要的数据

表连接的类型
内连接:inner join 或者 join (显示的是左右表都有完整字段值的记录)
左外连接:left outer join (保证左表数据的完整性)

示例
查询1702班的所有学生
select s.name,s.age from t_student s, t_class c where s.class_id = c.id and c.name = ‘1702’

二、主要函数

1.打开数据库:int sqlite3_open( 文件路径, sqlite3 ** );
用这个函数开始数据库操作。
需要传入两个参数,一是数据库文件路径,比如:c:\Database.db。
文件名不需要一定存在,如果此文件不存在,sqlite 会自动建立它。如果它存在,就尝试把它当数据库文件来打开。函数返回值表示操作是否正确,如果是 SQLITE_OK 则表示操作正常。相关的返回值sqlite定义了一些宏。具体这些宏的含义可以参考 sqlite3.h 文件。里面有详细定义.

2.关闭数据库:int sqlite3_close(sqlite3 *);
前面如果用 sqlite3_open 开启了一个数据库,结尾时不要忘了用这个函数关闭数据库。

数据库打开关闭代码示例:

    //创建数据库(打开)
    NSString *documensPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [documensPath stringByAppendingPathComponent:@"students.sql"];
    int result = sqlite3_open(path.UTF8String, &_database);
    if (result == SQLITE_OK) {
        NSLog(@"数据库打开成功!");

        //创建表
        char *msg = NULL;
        int createResult = sqlite3_exec(_database, "create table if not exists t_student (id integer primary key autoincrement, name text not null, age integer default 1);", NULL, NULL, &msg);
        if (createResult == SQLITE_OK) {
            NSLog(@"建表成功!");
        }
        else
        {
            NSLog(@"建表失败:%s", msg);
        }
    }
    else
    {
        sqlite3_close(_database);
        NSLog(@"数据库打开失败!");
    }

3.执行sql语句:int sqlite3_exec(sqlite3*, const char sql, sqlite3_callback, void , char **errmsg );
这就是执行一条 sql 语句的函数。
第1个参数不再说了,是前面open函数得到的指针。
第2个参数const char *sql 是一条 sql 语句,以\0结尾。
第3个参数sqlite3_callback 是回调,当这条语句执行之后,sqlite3会去调用你提供的这个函数。
第4个参数void * 是你所提供的指针,你可以传递任何一个指针参数到这里,这个参数最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL。等下我们再看回调函数的写法,以及这个参数的使用。
第5个参数char * errmsg 是错误信息。注意是指针的指针。sqlite3里面有很多固定的错误信息。执行 sqlite3_exec 之后,执行失败时可以查阅这个指针(直接 printf(“%s\n”,errmsg))得到一串字符串信息,这串信息告诉你错在什么地方。sqlite3_exec函数通过修改你传入的指针的指 针,把你提供的指针指向错误提示信息,这样sqlite3_exec函数外面就可以通过这个 char得到具体错误提示。

说明:通常,sqlite3_callback 和它后面的 void * 这两个位置都可以填 NULL。填NULL表示你不需要回调。比如你做 insert 操作,做 delete 操作,就没有必要使用回调。而当你做 select 时,就要使用回调,因为 sqlite3 把数据查出来,得通过回调告诉你查出了什么数据。

执行没有回调的代码示例:

    NSString *sqlStr = @"insert into t_student (name, age) values ('张三', 10);";
    char *msg = NULL;
    int result = sqlite3_exec(_database, sqlStr.UTF8String, NULL, NULL, &msg);
    if (result == SQLITE_OK) {
        NSLog(@"插入数据成功!");

        self.dataArr = [self getAllStudents];
        if (self.dataArr.count > 0) {
            [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
    else
    {
        NSLog(@"插入数据失败!");
    }

执行有回调的代码示例:

//回调函数
int callback(void *para, int n_column, char **column_value, char **column_name)
{
    StudentModel *model = [[StudentModel alloc] init];
    NSMutableArray *studentArr = (__bridge NSMutableArray *)para;
    for (int index = 0; index < n_column; index++) {
        switch (index) {
            case 0:
            {
                char *Id = column_value[index];
                model.idStr = Id ? [NSString stringWithUTF8String:Id] : @"";
            }
                break;
            case 1:
            {
                char *name = column_value[index];
                model.name = name ? [NSString stringWithUTF8String:name] : @"";
            }
                break;
            case 2:
            {
                char *age = column_value[index];
                model.age = age ? [NSString stringWithUTF8String:age] : @"";
            }
                break;

            default:
                break;
        }
    }

    [studentArr addObject:model];

    return 0;
}

- (NSArray *)getAllStudents
{
    NSMutableArray *studentArr = [NSMutableArray arrayWithCapacity:1];
    char *errorMsg = NULL;
    if (sqlite3_exec(_database, [NSString stringWithFormat:@"select id, name, age from t_student"].UTF8String, callback, (__bridge_retained  void *)studentArr, &errorMsg) != SQLITE_OK) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithUTF8String:errorMsg] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }

    return studentArr;
}

3.sqlite3_prepare(), 准备sql语句,执行select语句或者要使用parameter bind时,用这个函数(封装了sqlite3_exec.

4.sqlite3_bind_int(stmt, 1, 1);邦定参数,主要用于参数化查询.

5.sqlite3_step(), 在调用sqlite3_prepare后,使用这个函数在记录集中移动。

6.sqlite3_finalize(stmt);释放sql文资源

代码示例:

    NSMutableArray *studentArr = [NSMutableArray arrayWithCapacity:1];
    NSString *sqlStr = @"select id, name, age from t_student where name like ?;";// where name like '?'
    //sqlite3_stmt存放结果集的结构体
    sqlite3_stmt *stmt = NULL;
    //检查查询语句是否合法
    int result = sqlite3_prepare_v2(_database, sqlStr.UTF8String, -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"查询语句合法!");
        sqlite3_bind_text(stmt, 1, "%%张三%%", -1, NULL);
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            StudentModel *model = [[StudentModel alloc] init];
            char *sId = (char *)sqlite3_column_text(stmt, 0);
            char *name = (char *)sqlite3_column_text(stmt, 1);
            char *age = (char *)sqlite3_column_text(stmt, 2);

            model.idStr = sId ? [NSString stringWithUTF8String:sId] : @"";
            model.name = name ? [NSString stringWithUTF8String:name] : @"";
            model.age = age ? [NSString stringWithUTF8String:age] : @"";

            [studentArr addObject:model];
        }

        sqlite3_finalize(stmt);
    }
    else
    {
        NSLog(@"查询语句不合法!");
    }

    return studentArr;

猜你喜欢

转载自blog.csdn.net/jiuchabaikaishui/article/details/56352865
今日推荐