sqlite的基本操作

2016.9.6:数据库的封装

1,只要在创建的时候创建一次即可

2,类方法中不能使用成员变量,需要将此变量变为static的即全局变量

3.数据库的操作:注意,一般我们在bundle中创建的数据库,是无法通过代码对此数据库进行操作,需要将该数据库转移到沙盒中才能对其进行操作。


数据库常用操作语句:

primary key 主键  即此列是唯一的

主键特性:唯一性

                    自增性

0,创建数据库(代码方式):

需要添加libsqlite3.0.tdb框架并导入#import <sqlite3.h>

扫描二维码关注公众号,回复: 358558 查看本文章

//1.创建空数据库文件 沙盒中数据库后缀一般db或bundle 

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

//    NSString *dataBasePath = [documentPath stringByAppendingPathComponent:@"test.bundle"];

    NSString *dataBasePath = [documentPath stringByAppendingPathComponent:@"test.db"];


sqlite3 *database = nil;

    //内部实现过程:如果没有数据库文件,就创建;否则,就打开

   int ret =  sqlite3_open([dataBasePath cStringUsingEncoding:NSUTF8StringEncoding], &database);//OUT:

    if (ret!= SQLITE_OK) {//0成功,非0失败

        NSLog(@"创建数据库文件失败");

        return;//失败后再操作无意义,故return

    }


1,创建表:

create table people (id integer primary key,name text,age integer);

注意,在插入数据时,单引号内不能回车,否则报错

2,插入记录

insert into people (id,name,age)values(1234,'Bob',18);

insert into people (name,age)values('Bob',18);

insert into people (id,name,age)values(1245,'Bob',18);

insert into people (name,age)values('Bob',18);

3,更新数据

update people set name = 'Magine';

4,有条件的更新数据

update people set name = 'ma'where id =1245;

update people set name ='lili' where id=1246;

update people set name ='lili' where id >30 and id<1240;

update people set name ='kiki' where id >130 or name = 'lili';

5,查询数据

select * from people where id =150;

select *from people where name = 'no’;

5.1,数据库模糊查询:

  LIKE模糊查询语句;   % sqlite语句中代表任意字符的符号   OR查询语句 

            sqlite中代表任一字符的符号是%(例如查询数据库中某个字段,且该字段包含“虾”的记录)

             SELECT * FROM t_food WHERE name LIKE '%虾%';    =>根据name字段查找记录,且name字段中包含虾字

              SELECT *FROM t_food WHERE name LIKE ‘虾%’;  => 根据name字段查找记录,且name字段以虾开头;同理可以查找以虾结尾的name字段

              [SELECT *FROM t_food WHERE name LIKE ‘%%%@%%;’,searchText]; //name字段包含searText字的记录

              [SELECT *FROM t_food WHERE name LIKE ‘%%%@%% OR price LIKE ‘%%%@%%;’,searchText,searchText];

             SELECT *FROM notification WHERE noti_id LIKE ‘%8%’;

             SELECT *(代表取哪些字段)


6,删除数据

delete from people where name = 'dd' and name = 'erer';

delete from people where name = 'ko';

7,常用书库操作条件符

where / and / or

8,清除表所有数据:delete from tableName

9,删除表:drop table tableName

10,删除数据库:用iOS原生类NSFileManager删除即可。


2016.9.2 :

sqlite 数据库如果为创建直接打开,则会先创建再打开

oc字符串转化为c字符串 char *c = ocString.UTF8string

c字符串转化为oc字符串NSString *ocString = [NSString stringWithUTF8String:charString];

sql语句:1.sqlite_exec() 词语句只适合查询语句,不适合有返回值得语句,创表,插入数据

             2.int status = sqlite_prepare_v2() 查询并返回数据做准备

             if(status == SQLITE_OK){//准备成功

              3.  white ( sqlite_step(stmt) == SQLITE_ROW ){//成功取出一条数据

                  

                   }

             }

     

猜你喜欢

转载自blog.csdn.net/denggun12345/article/details/54706431