數據庫(詳細步驟)

寫一個學生類 .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 加入到工程中

在這個工具類中引入頭文件

(1).引入要存數據的類的頭文件
(2).數據庫的頭文件
#import <sqlite3.h>
#import "Student.h"

在.h文件延展 用來保存數據庫的地址

@interface dataBaseTool : NSObject
{
// 用來保存數據庫對象的地址
sqlite3 *dbPoint;
}

爲了保證當前數據在工程裏是唯一的 ,我們用簡單單例的方式創建一個數據庫工具對象

(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語句出問題,所以保證語句沒問題,再放到工程裏使用
    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];
發佈了73 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章