IOS中数据库的编辑使用

来源:互联网 发布:麦考瑞大学 知乎 编辑:程序博客网 时间:2024/05/21 10:16

数据库有三种结构类型:层次式数据库,网状式数据库和关系型数据库。

常用数据库有SQL,MySQL和 Oracle数据库。

区别为:MySQL数据库为轻量级数据库;

              Oracle数据库经常用于存数大型数据。

在工程中使用数据库,需要先引用libsqlite3.dylib  

创建继承NSObject的DBPoint类

.h文件        

<pre name="code" class="html">#import  “sqlite3.h”+ (sqlite3 *)openDb;//对获取数据库的方法的声明

.m文件
#import "sqlite3.h"static sqlite3 *dbPoint = nil;//定义数据库指针 + (sqlite3 *)openDb{//获取数据库的方法   if(dbPoint){       return dbPoint;   }   NSArray*array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);          path = [NSString stringWithFormat:@"%@/db",path];   if ( ![[NSFileManager defaultManager] fileExistsAtPath:path]) {  //判断文件是否存在,使用文件管理类           //获得将要拷贝的文件的路径,bundle路径          NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"DataBase" ofType:@"sqlite"];       NSLog(@"source == %@",sourcePath);       NSError *error = nil;      //没有文件,就拷贝             [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:path error:&error];       if (error) {          NSLog(@"error===%@",error);       }   } //数据库代码,创建数据库的指针对象  sqlite3_open([path UTF8String], &dbPoint);   return dbPoint;   }

数据库有增删改查的功能,在工程中创建继承NSObject的类,在这个类中可以实现数据库的功能。

在.m文件中实现增删改查功能的方法

1.增加方法

+ (void)insertWithmodel:(Model *)model{    sqlite3 *db = [DB openDB];    NSString *sqlStr = [NSString stringWithFormat:@"insert into Novel (nv_id,nv_author,nv_bookname,nv_score)        values (%d,' %@','%@',%f) ",model.nid,model.author,model.bookname,model.score];    // 使用的是sqlite3_exec();    int result = sqlite3_exec(db, [sqlStr UTF8String], NULL, NULL, NULL);    if (result == SQLITE_OK) {        NSLog(@"添加成功");    }}


注意:添加语句中的字段名要和数据库中的字段名完全相同。

更新和删除只需要将数据库查询语句更改即可。

2.查询方法:在查询方法中需要制作替身来保存数据库语句得到的结果,然后对其结果进行查询操作。

sqlite3_stmt *stmt = nil;//制作替身NSString * sqlStr = [NSString stringWithFormat:@"select nv_id,nv_author,nv_bookname,nv_score from Novel"];//查询语句int result = sqlite3_prepare_v2(db, [sqlStr UTF8String], - 1, &stmt, NULL);//结果//参数:const char *zSql 是指查询语句;int nByte sql语句的长度限制;   if (result == SQLITE_OK) {//如果结果不是0,就去sdk中查找错误        //取数据        while (sqlite3_step(stmt) == SQLITE_ROW) {////链表的头指针下面有一条数据            int nid = sqlite3_column_int(stmt, 0);//int iCol 我取的是第几列,和sql语句中的顺序是相匹配的。取sql语句里面对应列名的顺序  从0开始            const unsigned char *nauthor = sqlite3_column_text(stmt, 1);//const unsigned char 无符号char类型            const unsigned char *nbookname = sqlite3_column_text(stmt, 2);            float nscore = sqlite3_column_double(stmt, 3);                       NSString *author = [NSString stringWithUTF8String:(const char *)nauthor];//强转成const char变转换称NSString类型            NSString *bookname = [NSString stringWithUTF8String:(const char *)nbookname];            Model *value = [Model modelWithId:nid author:author bookname:bookname score:nscore];            [results addObject:value];           }    }在取值完成后需要取消替身   //取消替身    sqlite3_finalize(stmt);    return  results;  }



0 0
原创粉丝点击