数据库(具体步骤)

写一个学生类 .h文件里定义四个属性

原代码:

@property(nonatomic ,copy)NSString *name;
@property(nonatomic ,copy)NSString *sex;
@property(nonatomic ,copy)NSString *hobby;
@property(nonatomic ,assign)NSInteger age;

创建一个数据库工具:继承于NSObject

在这之前要先找到一个框架 libsqlite3.0.dylib 加入到project中

在这个工具类中引入头文件

(1).引入要存数据的类的头文件
(2).数据库的头文件
#import <sqlite3.h>
#import "Student.h"

在.h文件延展 用来保存数据库的地址

@interface dataBaseTool : NSObject
{
// 用来保存数据库对象的地址
sqlite3 *dbPoint;
}

为了保证当前数据在project里是唯一的 ,我们用简单单例的方式创建一个数据库工具对象

(1).在.h文件里写一个方法

+ (dataBaseTool *)sharDataBaseTool;

(2).在.m文件里写实现方法

+ (dataBaseTool *)sharDataBaseTool{
    static dataBaseTool *tool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool =[[dataBaseTool alloc] init];
    });
    return tool;
}

1.打开数据库

(1).在.h文件里创建方法

-(void)openDB;

(2).在.m文件里实现方法

-(void)openDB{
  // 数据库文件也保存在沙盒的documents文件里, 所以先找沙盒路径
  NSArray *sandBox =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
  NSString *sandBoxPath =sandBox[0];

  // 拼接文件路径 ,假设系统依据这个文件路径查找的时候有相应文件则直接打开数据库,假设没有则会创建一个相应的数据库   NSString *documentPath =[sandBoxPath stringByAppendingPathComponent:@"Student.sqlite"];   
  int result =sqlite3_open([documentPath UTF8String], &dbPoint);
  if (result == SQLITE_OK) {
        NSLog(@"数据库打开成功");
        NSLog(@"%@",documentPath);
  }else{
        NSLog(@"数据库打开失败");
  }

}

(3).在viewController中调用

引入student类和dateBaseTool数据库的头文件
 #import "dataBaseTool.h"
 #import "Student.h"
 调用:
[[dataBaseTool sharDataBaseTool] openDB];

2 .给数据库创建张表格 ,table

(1).在.h文件里定义方法:

-(void)createTable;

(2).在.m文件里实现方法

-(void)createTable{

 // primary key 是主键的意思 ,主键在当前表格前表里数据是唯一的,不能反复,能够是唯一的标示一条数据,通常是整数
    // zutoincrement自增 ,为了让主键不反复,会让主键採用自增的方式
    // if not exists 假设没有表才会创建,防止反复创建覆盖之前数据
    // 数据库问题%90是sql语句出问题,所以保证语句没问题,再放到project里使用
    NSString *sqlStr =@"create table if not exists stu(number integer primary key autoincrement, name text, sex text, age integer, hobby text)";
    // 运行这条sql语句
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"表创建成功");
    }else {
        NSLog(@"表创建失败");
    }

}

(3).调用

[[dataBaseTool sharDataBaseTool] createTable];

3.向表里插入一个学生信息

(1).h

-(void)insertStu:(Student *)stu;

(2).m

-(void)insertStu:(Student *)stu{
    // 语句里值的位置要加上单引號
    NSString *sqlStr =[NSString stringWithFormat:@"insert into stu (name, age, sex, hobby) values ('%@', %ld, '%@', '%@')", stu.name, stu.age, stu.sex ,stu.hobby];

// 运行sql语句
    int result =sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"加入学生成功");
    }else{
        NSLog(@"加入学生失败");
    }
}

(3).调用

创建一个stu  
Student *stu =[[Student alloc] init];
    stu.name =@"zhang";
    stu.age =20;
    stu.sex =@"nan";
    stu.hobby =@"ying";
    // 调用加入的方法
    [[dataBaseTool sharDataBaseTool] insertStu:stu];

4.更新表里的学生数据

(1).h

- (void)updateStu:(Student *)stu;

(2).m

- (void)updateStu:(Student *)stu{
    NSString *sqlStr = [NSString stringWithFormat:@"update stu set name = '%@', sex = '%@', hobby = '%@', age = %ld where name = '%@'",stu.name, stu.sex, stu.hobby ,stu.age,stu.name];
    // 运行sql语句
    int result =sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"更新成功");
    }else{
        NSLog(@"更新失败");
    }

}

(3).调用

创建一个stu
Student *stu =[[Student alloc] init];
stu.name =@"zhang";
stu.sex =@"nan";
stu.hobby =@"xuexi";
stu.age =30;
调用
[[dataBaseTool sharDataBaseTool] updateStu:stu];

5.删除数据

(1).h

-(void)deleteStu:(Student *)stu;

(2).m

-(void)deleteStu:(Student *)stu{
    NSString *sqlStr =[NSString stringWithFormat:@"delete from stu where name = '%@'",stu.name];
    int result =sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
}

(3).调用

删除 学生名字是zhang的学生信息
 Student *stu =[[Student alloc] init];
    stu.name =@"zhang";   
 [[dataBaseTool sharDataBaseTool] deleteStu:stu];

6. 查询数据库中全部学生表里的数据

(1).h

-(NSMutableArray *)selectAllStu;

(2).m

-(NSMutableArray *)selectAllStu{
 // 查询逻辑
    // 1.先从本地的数据库中读取某张表里的全部数据
    // 2.然后逐条进行读取,对model进行赋值
    // 3.把已经赋值好的model放到数组中,而且返回
    NSString *sqlStr =@"select * from stu";
    // 在语句里 * 是通配符的意思 ,通过一个 *相当于取代了表里的全部的字段名
    // 接下来须要定义一个尾随指针,他用来遍历数据库表里中的每行数据
    sqlite3_stmt *stmt =nil;
    // 第三个參数:查询语句字数限制 , -1是没有限制
    int result =sqlite3_prepare_v2(dbPoint, [sqlStr UTF8String], -1, &stmt, nil);
    // 这种方法相当于把数据库和尾随指针相关联,一同完毕查询功能
    // 初始化一个用来装学生的数组
    NSMutableArray *stuArr =[NSMutableArray array];
    if (result == SQLITE_OK ){
        NSLog(@"查询成功");
        // 開始便利查询数据库的每一行
       while(sqlite3_step(stmt)== SQLITE_ROW){
 // 让尾随指针进行便利查询, 假设没有行,才会停止循环
// 满足条件,则逐列的读取这一行上的数据
// 第二个參数表示当前这列数据在表中的第几列
           const unsigned char *name =sqlite3_column_text(stmt, 1);
           const unsigned char *sex = sqlite3_column_text(stmt, 2);
           int age =sqlite3_column_int(stmt, 3);
           const unsigned char *hobby  =sqlite3_column_text(stmt, 4);
           // 把列里面的数据在进行类型的转换
           NSInteger stuAge = age;
           NSString *stuName =[NSString stringWithUTF8String:(const char*)name];
           NSString *stuSex =[NSString stringWithUTF8String:(const char*)sex];
           NSString *stuHobby =[NSString stringWithUTF8String:(const char*)hobby];
 // 给对象赋值 ,然后把对象放到数组里
           Student *stu =[[Student alloc] init];
           stu.name =stuName;
           stu.sex =stuSex;
           stu.hobby =stuHobby;
           stu.age =stuAge;
           [stuArr addObject:stu];
        }
    }else{
        NSLog(@"查询失败");
        NSLog(@"%d",result);
    }       
 return stuArr;

}

(3).调用

创建数组接收数据
NSMutableArray *arr =[[dataBaseTool sharDataBaseTool] selectAllStu];
遍历数组    
for (Student *stu in arr) {
        NSLog(@"%@",stu.name);
    }

7.关闭数据库

(1).h

-(void)closeDB;

(2).m

-(void)closeDB{
    int result =sqlite3_close(dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"数据关闭成功");
    }else{
 NSLog(@"数据关闭失败");
    }    
}

(3).调用

[[dataBaseTool sharDataBaseTool ] closeDB];
原文地址:https://www.cnblogs.com/mfmdaoyou/p/7091429.html