SQL_增刪改查

添加庫

 libsqlite3.tbd
#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    
    // 更改主窗口
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];
    
    
    return YES;
}

.h

#import <Foundation/Foundation.h>

@interface ClassMessage : NSObject

// 數(shù)據(jù)庫必須得有一個(gè)主鍵id
@property (nonatomic ,assign) NSInteger classid;

// 定義屬性
@property (nonatomic ,strong) NSString *name, *age, *sex, *height, *weight;


@end

.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>         // 庫的頭文件
#import "ClassMessage.h"    // 數(shù)據(jù)的頭文件

@interface SqlData : NSObject

// 數(shù)據(jù)庫的后綴名:db

// 定義全局變量
{
    sqlite3 *db;
}


// 單例方法 *** --- 采用類方法
+(instancetype)initData;

// 初始化數(shù)據(jù)庫 ***
-(void)initSql;

// 初始化數(shù)據(jù)庫表格 ***
-(void)initTable;

// 添加數(shù)據(jù)
-(void)addData:(ClassMessage *)data;

// 修改數(shù)據(jù)
-(void)changeData:(ClassMessage *)data;

// 刪除數(shù)據(jù)
-(void)deleteData:(NSInteger)deldata;

// 查詢數(shù)據(jù)
-(NSMutableArray *)showAllArr;

// 關(guān)閉數(shù)據(jù) ***
-(void)closeSql;



@end

.m

#import "SqlData.h"

// 創(chuàng)建一個(gè)靜態(tài)變量
static SqlData *sqlData;

@implementation SqlData

// 單例方法 *** --- 采用類方法
+(instancetype)initData
{
    // 判斷,如果沒有創(chuàng)建靜態(tài)變量,就創(chuàng)建
    if (!sqlData) {
        
        sqlData = [[SqlData alloc] init];
    }
    return sqlData;
}


// 初始化數(shù)據(jù)庫 ***
-(void)initSql
{
    // 默認(rèn)數(shù)據(jù)存儲(chǔ)在沙盒里
    // 獲取存儲(chǔ)沙盒的路徑 --- Documents目錄(路徑)
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    // 拼接 ---- 數(shù)據(jù)庫的名字
    NSString *strName = [str stringByAppendingString:@"/1511E.db"];
    // 對(duì)數(shù)據(jù)庫進(jìn)行判斷 ---- UTF8String:轉(zhuǎn)換為中文的格式 ---- **:指的是指針指向的對(duì)象的地址 --- SQLITE_OK:如果是這個(gè)狀態(tài),表示數(shù)據(jù)庫打開成功
    if (sqlite3_open([strName UTF8String], &db) == SQLITE_OK) {
        
        NSLog(@"數(shù)據(jù)庫打開成功");
        
        // 數(shù)據(jù)庫的表格
        [self initTable];
        
    }else{
    
        NSLog(@"數(shù)據(jù)庫打開失敗");
    }
    
}

// 初始化數(shù)據(jù)庫表格 ***
-(void)initTable
{
    // 使用數(shù)據(jù)庫里的 sql 語句
    // 初始化數(shù)據(jù)庫表格 -- 格式 -- create table if not exists 表名(主鍵盤id integer primary key, 所有的數(shù)據(jù)類型(*name, *age, *sex, *height, *weight));
    // 創(chuàng)建表格時(shí),如果沒有執(zhí)行 exists 就進(jìn)行創(chuàng)建
    // const 常量 -- 不能發(fā)生改變的量 --- ""引號(hào)中不可以使用中文 --- exists后的表名可隨便定義
    const char *sql = "create table if not exists ClassMessage(classid integer primary key, name text, age text, sex text, height text, weight text)";
    
    // 預(yù)編譯數(shù)據(jù)庫的指針
    sqlite3_stmt *stmt;
    
    // 綁定數(shù)據(jù)庫指針的一個(gè)接口 --- 0 表示為空,-1 自動(dòng)匹配長(zhǎng)度,1 固定范圍,定義多少,就是多少
    // 打開數(shù)據(jù)庫的接口 --- 搭建橋梁
    sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    
    // 執(zhí)行預(yù)編譯接口 -- step:執(zhí)行
//    sqlite3_step(stmt);
    
    // 判斷 一行一行的去判斷是否執(zhí)行完成
    if (sqlite3_step(stmt) == SQLITE_DONE) {
        
        NSLog(@"數(shù)據(jù)庫表格創(chuàng)建成功");
    }else{
    
        NSLog(@"數(shù)據(jù)庫表格創(chuàng)建失敗");
    }
    
    // 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰
    sqlite3_finalize(stmt);
    
}

// 添加數(shù)據(jù)
-(void)addData:(ClassMessage *)data
{
    // 添加數(shù)據(jù)的 sql 語句:insert into 表名 values(null,?,?,?,?,?);
    const char *sql = "insert into ClassMessage values(null,?,?,?,?,?)";
    
    // 預(yù)編譯數(shù)據(jù)庫的指針
    sqlite3_stmt *stmt;
    
    // 綁定數(shù)據(jù)庫指針的一個(gè)接口 --- 0 表示為空,-1 自動(dòng)匹配長(zhǎng)度,1 固定范圍,定義多少,就是多少
    // 打開數(shù)據(jù)庫的接口 --- 搭建橋梁
    sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    
    // 調(diào)用添加數(shù)據(jù)庫的接口
    // 綁定數(shù)據(jù)庫接口  ---- transient
    sqlite3_bind_text(stmt, 1, [data.name UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 2, [data.age UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 3, [data.sex UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 4, [data.height UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 5, [data.weight UTF8String], -1, SQLITE_TRANSIENT);
    
    // 執(zhí)行預(yù)編譯接口 -- step:執(zhí)行
    sqlite3_step(stmt);
    
    // 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰
    sqlite3_finalize(stmt);

}

// 修改數(shù)據(jù)
-(void)changeData:(ClassMessage *)data
{
    // 使用 sql 語句的格式:update 表名 set 所有的數(shù)據(jù)類型 where 主鍵id = ?
    const char *sql = "update ClassMessage set name = ?, age = ?, sex = ?, height = ?, weight = ? where classid = ?";
    
    // 預(yù)編譯指針(作用:鏈接到數(shù)據(jù)庫)
    sqlite3_stmt *stmt;
    // 綁定數(shù)據(jù)庫指針的接口
    sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    
    // 綁定數(shù)據(jù)庫接口  ---- transient
    sqlite3_bind_text(stmt, 1, [data.name UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 2, [data.age UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 3, [data.sex UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 4, [data.height UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 5, [data.weight UTF8String], -1, SQLITE_TRANSIENT);
    
    // 綁定主鍵id
    sqlite3_bind_int(stmt, 6, (int)(data.classid));
    
    // 執(zhí)行預(yù)編譯接口 -- step:執(zhí)行
    sqlite3_step(stmt);
    
    // 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰
    sqlite3_finalize(stmt);

    
}

// 刪除數(shù)據(jù)
-(void)deleteData:(NSInteger)deldata
{
    // sql 語句: delete from 表名 where 表名的主鍵id = ?
    const char *sql = "delete from ClassMessage where classid = ?";
    
    // 預(yù)編譯指針(作用:鏈接到數(shù)據(jù)庫)
    sqlite3_stmt *stmt;
    // 綁定數(shù)據(jù)庫指針的接口
    sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    
    // 刪除綁定主鍵id -- 即刪除數(shù)據(jù)
    sqlite3_bind_int(stmt, 1, (int)(deldata));
    
    // 執(zhí)行預(yù)編譯接口 -- step:執(zhí)行
    sqlite3_step(stmt);
    
    // 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰
    sqlite3_finalize(stmt);
    
}

// 查詢數(shù)據(jù)
-(NSMutableArray *)showAllArr
{
    // sql 語句:select *from 表名 --- 查詢?nèi)?    // sql 語句:select *from 表名 where 主鍵id = ? ---- 查詢單行
    
    const char *sql = "select *from ClassMessage";
    
    // 預(yù)編譯指針(作用:鏈接到數(shù)據(jù)庫)
    sqlite3_stmt *stmt;
    // 綁定數(shù)據(jù)庫指針的接口
    sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    
    // 所有的數(shù)組都是以數(shù)組的形式存儲(chǔ)的
    // 創(chuàng)建數(shù)組
    NSMutableArray *arr = [NSMutableArray array];
    
    // 執(zhí)行數(shù)據(jù)庫中的預(yù)編譯接口  ----- SQLITE_ROW 表示一行一行的去查詢數(shù)據(jù)庫中的數(shù)據(jù)
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        
        ClassMessage *classData = [[ClassMessage alloc] init];
        
        // 找到表格中的主鍵 ---- sqlite3_column_XXX (XXX表示數(shù)據(jù)類型) 表示返回當(dāng)前行(指的是列的數(shù)據(jù))
        classData.classid = sqlite3_column_int(stmt, 0);
        classData.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
        classData.age = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
        classData.sex = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
        classData.height = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)];
        classData.weight = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 5)];
        
        // 將數(shù)據(jù)添加到數(shù)組里
        [arr addObject:classData];
    }
    
    // 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰
    sqlite3_finalize(stmt);
    
    // 返回
    return arr;
}

// 關(guān)閉數(shù)據(jù) ***
-(void)closeSql
{
    sqlite3_close(db);
}



@end

.h

#import <UIKit/UIKit.h>

@interface ClassView : UIView

// 定義屬性
@property (nonatomic ,strong) UITextField *nameTf, *ageTf, *sexTf, *heightTf, *weightTf;

@end

.m

#import "ClassView.h"

@implementation ClassView

// 單例方法
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self addSubview:self.nameTf];
        [self addSubview:self.ageTf];
        [self addSubview:self.sexTf];
        [self addSubview:self.heightTf];
        [self addSubview:self.weightTf];
    }
    return self;
}

// 懶加載
// 名字
-(UITextField *)nameTf
{
    if (!_nameTf) {
        
        _nameTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 100, self.frame.size.width, 50)];
        _nameTf.borderStyle = UITextBorderStyleRoundedRect;
        _nameTf.placeholder = @"名字";
        _nameTf.textAlignment = NSTextAlignmentCenter;
    }
    return _nameTf;
}
// 年齡
-(UITextField *)ageTf
{
    if (!_ageTf) {
        
        _ageTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 160, self.frame.size.width, 50)];
        _ageTf.borderStyle = UITextBorderStyleRoundedRect;
        _ageTf.placeholder = @"年齡";
        _ageTf.textAlignment = NSTextAlignmentCenter;
    }
    return _ageTf;
}
// 性別
-(UITextField *)sexTf
{
    if (!_sexTf) {
        
        _sexTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 220, self.frame.size.width, 50)];
        _sexTf.borderStyle = UITextBorderStyleRoundedRect;
        _sexTf.placeholder = @"性別";
        _sexTf.textAlignment = NSTextAlignmentCenter;
    }
    return _sexTf;
}
// 身高
-(UITextField *)heightTf
{
    if (!_heightTf) {
        
        _heightTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 280, self.frame.size.width, 50)];
        _heightTf.borderStyle = UITextBorderStyleRoundedRect;
        _heightTf.placeholder = @"身高";
        _heightTf.textAlignment = NSTextAlignmentCenter;
    }
    return _heightTf;
}
// 體重
-(UITextField *)weightTf
{
    if (!_weightTf) {
        
        _weightTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 340, self.frame.size.width, 50)];
        _weightTf.borderStyle = UITextBorderStyleRoundedRect;
        _weightTf.placeholder = @"體重";
        _weightTf.textAlignment = NSTextAlignmentCenter;
    }
    return _weightTf;
}


@end

ViewController.h--- ViewController 改成 UITableViewController

.m

#import "ViewController.h"
#import "SqlData.h" // 測(cè)試用頭文件
#import "ClassMessage.h"
#import "SecViewController.h"

@interface ViewController ()

{
    NSMutableArray *array;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 測(cè)試用
    // 先調(diào)用類方法,再通過類方法調(diào)用實(shí)例方法
    //[[SqlData initData] initSql];
    
    // 標(biāo)題
    self.title = @"數(shù)據(jù)庫";
    
    // 表格行高
    self.tableView.rowHeight = 150;
    
    // 初始化數(shù)組
    array = [NSMutableArray array];
    
    // 跳轉(zhuǎn)按鈕
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(tiaozhuan)];
    
    
}

// 實(shí)現(xiàn)跳轉(zhuǎn)按鈕點(diǎn)擊事件
-(void)tiaozhuan
{
    // 創(chuàng)建下一個(gè)頁面的主頁面
    SecViewController *secVC = [[SecViewController alloc] init];
    
    // 執(zhí)行跳轉(zhuǎn) -- 左右側(cè)滑
    [self.navigationController pushViewController:secVC animated:YES];
}

// 視圖將要顯示
-(void)viewWillAppear:(BOOL)animated
{
    // 調(diào)用數(shù)據(jù)庫方法
    [[SqlData initData] initSql];
    // 調(diào)用數(shù)據(jù)庫 查詢方法
    array = [[SqlData initData] showAllArr];
    // 關(guān)閉數(shù)據(jù)庫
    [[SqlData initData] closeSql];
    
    // 刷新表格
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark UITableViewDataSource
// 行數(shù)
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return array.count;
}
// 單元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 查找 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
    // 如果找不到就創(chuàng)建 cell
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    }
    
    // 初始化對(duì)象
    ClassMessage *classMsg = array[indexPath.row];
    
    // 設(shè)置內(nèi)容
    cell.textLabel.text = [NSString stringWithFormat:@"%ld\n%@\n%@\n%@\n%@\n%@",classMsg.classid, classMsg.name, classMsg.age, classMsg.sex, classMsg.height, classMsg.weight];
    
    // 自動(dòng)換行
    cell.textLabel.numberOfLines = 0;
    
    // 返回 cell
    return cell;
    
}

// 點(diǎn)擊表格跳轉(zhuǎn)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 創(chuàng)建下一面的主頁面
    SecViewController *secV = [[SecViewController alloc] init];
    
    // 屬性傳值
    secV.message = array[indexPath.row];
    
    // 跳轉(zhuǎn)
    [self.navigationController pushViewController:secV animated:YES];
}

// 刪除行
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[SqlData initData] initSql];
    // 獲取數(shù)據(jù)庫中的數(shù)據(jù) --- 刪除主鍵id
    [[SqlData initData] deleteData:[array[indexPath.row] classid]];
    // 關(guān)閉數(shù)據(jù)庫
    [[SqlData initData] closeSql];
    
    // 刪除數(shù)據(jù)
    [array removeObject:array[indexPath.row]];
    
    // 刷新表格
    [self.tableView reloadData];
}


@end

.h

#import <UIKit/UIKit.h>
#import "ClassMessage.h"

@interface SecViewController : UIViewController

// 定義屬性
@property (nonatomic ,strong) ClassMessage *message;

@end

.m

#import "SecViewController.h"
#import "ClassView.h"
#import "ClassMessage.h"
#import "SqlData.h"

@interface SecViewController ()

{
    ClassView *classView;
}

@end

@implementation SecViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化視圖
    classView = [[ClassView alloc] initWithFrame:self.view.frame];
    classView.backgroundColor = [UIColor magentaColor];
    self.view = classView;
    
    // 傳值
    classView.nameTf.text = self.message.name;
    classView.ageTf.text = self.message.age;
    classView.sexTf.text = self.message.sex;
    classView.heightTf.text = self.message.height;
    classView.weightTf.text = self.message.weight;
    
    // 判斷添加標(biāo)題
    if (classView.nameTf.text.length <= 0) {
        
        self.title = @"添加數(shù)據(jù)";
        // 創(chuàng)建添加按鈕
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(didClickAdd)];
    }else{
    
        self.title = @"修改數(shù)據(jù)";
        // 創(chuàng)建修改按鈕
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(didClickSave)];
    }
    
    
    
}

// 實(shí)現(xiàn) 添加按鈕點(diǎn)擊事件
-(void)didClickAdd
{
    // 初始化對(duì)象
    ClassMessage *classMessage = [[ClassMessage alloc] init];
    // 賦值
    classMessage.name = classView.nameTf.text;
    classMessage.age = classView.ageTf.text;
    classMessage.sex = classView.sexTf.text;
    classMessage.height = classView.heightTf.text;
    classMessage.weight = classView.weightTf.text;
    
    // 調(diào)用數(shù)據(jù)庫方法
    [[SqlData initData] initSql];
    // 調(diào)用添加數(shù)據(jù)庫方法
    [[SqlData initData] addData:classMessage];
    // 調(diào)用關(guān)閉數(shù)據(jù)庫方法
    [[SqlData initData] closeSql];
    
    // 跳轉(zhuǎn)回上一視圖
    [self.navigationController popViewControllerAnimated:YES];
}

//  實(shí)現(xiàn) 修改按鈕點(diǎn)擊事件
-(void)didClickSave
{
    // 切記!!!別初始化數(shù)據(jù)源類 ***
    self.message.name = classView.nameTf.text;
    self.message.age = classView.ageTf.text;
    self.message.sex = classView.sexTf.text;
    self.message.height = classView.heightTf.text;
    self.message.weight = classView.weightTf.text;
    
    // 調(diào)用數(shù)據(jù)庫的單例方法
    [[SqlData initData] initSql];
    [[SqlData initData] changeData:self.message];
    [[SqlData initData] closeSql];
    
    // 跳轉(zhuǎn)回上一視圖
    [self.navigationController popViewControllerAnimated:YES];
    
}


@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容