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

@interface ClassMessage : NSObject

// 數據庫必須得有一個主鍵id

@property (nonatomic ,assign) NSInteger classid;

// 定義屬性

@property (nonatomic ,strong) NSString *name, *age, *sex, *height, *weight;

@end

.h

#import

#import ? ? ? ? // 庫的頭文件

#import "ClassMessage.h"? ? // 數據的頭文件

@interface SqlData : NSObject

// 數據庫的后綴名:db

// 定義全局變量

{

sqlite3 *db;

}

// 單例方法 *** --- 采用類方法

+(instancetype)initData;

// 初始化數據庫 ***

-(void)initSql;

// 初始化數據庫表格 ***

-(void)initTable;

// 添加數據

-(void)addData:(ClassMessage *)data;

// 修改數據

-(void)changeData:(ClassMessage *)data;

// 刪除數據

-(void)deleteData:(NSInteger)deldata;

// 查詢數據

-(NSMutableArray *)showAllArr;

// 關閉數據 ***

-(void)closeSql;

@end

.m

#import "SqlData.h"

// 創(chuàng)建一個靜態(tài)變量

static SqlData *sqlData;

@implementation SqlData

// 單例方法 *** --- 采用類方法

+(instancetype)initData

{

// 判斷,如果沒有創(chuàng)建靜態(tài)變量,就創(chuàng)建

if (!sqlData) {

sqlData = [[SqlData alloc] init];

}

return sqlData;

}

// 初始化數據庫 ***

-(void)initSql

{

// 默認數據存儲在沙盒里

// 獲取存儲沙盒的路徑 --- Documents目錄(路徑)

NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

// 拼接 ---- 數據庫的名字

NSString *strName = [str stringByAppendingString:@"/1511E.db"];

// 對數據庫進行判斷 ---- UTF8String:轉換為中文的格式 ---- **:指的是指針指向的對象的地址 --- SQLITE_OK:如果是這個狀態(tài),表示數據庫打開成功

if (sqlite3_open([strName UTF8String], &db) == SQLITE_OK) {

NSLog(@"數據庫打開成功");

// 數據庫的表格

[self initTable];

}else{

NSLog(@"數據庫打開失敗");

}

}

// 初始化數據庫表格 ***

-(void)initTable

{

// 使用數據庫里的 sql 語句

// 初始化數據庫表格 -- 格式 -- create table if not exists 表名(主鍵盤id integer primary key, 所有的數據類型(*name, *age, *sex, *height, *weight));

// 創(chuàng)建表格時,如果沒有執(zhí)行 exists 就進行創(chuàng)建

// const 常量 -- 不能發(fā)生改變的量 --- ""引號中不可以使用中文 --- exists后的表名可隨便定義

const char *sql = "create table if not exists ClassMessage(classid integer primary key, name text, age text, sex text, height text, weight text)";

// 預編譯數據庫的指針

sqlite3_stmt *stmt;

// 綁定數據庫指針的一個接口 --- 0 表示為空,-1 自動匹配長度,1 固定范圍,定義多少,就是多少

// 打開數據庫的接口 --- 搭建橋梁

sqlite3_prepare_v2(db, sql, -1, &stmt, nil);

// 執(zhí)行預編譯接口 -- step:執(zhí)行

//? ? sqlite3_step(stmt);

// 判斷 一行一行的去判斷是否執(zhí)行完成

if (sqlite3_step(stmt) == SQLITE_DONE) {

NSLog(@"數據庫表格創(chuàng)建成功");

}else{

NSLog(@"數據庫表格創(chuàng)建失敗");

}

// 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰

sqlite3_finalize(stmt);

}

// 添加數據

-(void)addData:(ClassMessage *)data

{

// 添加數據的 sql 語句:insert into 表名 values(null,?,?,?,?,?);

const char *sql = "insert into ClassMessage values(null,?,?,?,?,?)";

// 預編譯數據庫的指針

sqlite3_stmt *stmt;

// 綁定數據庫指針的一個接口 --- 0 表示為空,-1 自動匹配長度,1 固定范圍,定義多少,就是多少

// 打開數據庫的接口 --- 搭建橋梁

sqlite3_prepare_v2(db, sql, -1, &stmt, nil);

// 調用添加數據庫的接口

// 綁定數據庫接口? ---- 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í)行預編譯接口 -- step:執(zhí)行

sqlite3_step(stmt);

// 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰

sqlite3_finalize(stmt);

}

// 修改數據

-(void)changeData:(ClassMessage *)data

{

// 使用 sql 語句的格式:update 表名 set 所有的數據類型 where 主鍵id = ?

const char *sql = "update ClassMessage set name = ?, age = ?, sex = ?, height = ?, weight = ? where classid = ?";

// 預編譯指針(作用:鏈接到數據庫)

sqlite3_stmt *stmt;

// 綁定數據庫指針的接口

sqlite3_prepare_v2(db, sql, -1, &stmt, nil);

// 綁定數據庫接口? ---- 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í)行預編譯接口 -- step:執(zhí)行

sqlite3_step(stmt);

// 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰

sqlite3_finalize(stmt);

}

// 刪除數據

-(void)deleteData:(NSInteger)deldata

{

// sql 語句: delete from 表名 where 表名的主鍵id = ?

const char *sql = "delete from ClassMessage where classid = ?";

// 預編譯指針(作用:鏈接到數據庫)

sqlite3_stmt *stmt;

// 綁定數據庫指針的接口

sqlite3_prepare_v2(db, sql, -1, &stmt, nil);

// 刪除綁定主鍵id -- 即刪除數據

sqlite3_bind_int(stmt, 1, (int)(deldata));

// 執(zhí)行預編譯接口 -- step:執(zhí)行

sqlite3_step(stmt);

// 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰

sqlite3_finalize(stmt);

}

// 查詢數據

-(NSMutableArray *)showAllArr

{

// sql 語句:select *from 表名 --- 查詢全部

// sql 語句:select *from 表名 where 主鍵id = ? ---- 查詢單行

const char *sql = "select *from ClassMessage";

// 預編譯指針(作用:鏈接到數據庫)

sqlite3_stmt *stmt;

// 綁定數據庫指針的接口

sqlite3_prepare_v2(db, sql, -1, &stmt, nil);

// 所有的數組都是以數組的形式存儲的

// 創(chuàng)建數組

NSMutableArray *arr = [NSMutableArray array];

// 執(zhí)行數據庫中的預編譯接口? ----- SQLITE_ROW 表示一行一行的去查詢數據庫中的數據

while (sqlite3_step(stmt) == SQLITE_ROW) {

ClassMessage *classData = [[ClassMessage alloc] init];

// 找到表格中的主鍵 ---- sqlite3_column_XXX (XXX表示數據類型) 表示返回當前行(指的是列的數據)

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)];

// 將數據添加到數組里

[arr addObject:classData];

}

// 銷毀接口 -- 防止有空指針和野指針,造成程序崩潰

sqlite3_finalize(stmt);

// 返回

return arr;

}

// 關閉數據 ***

-(void)closeSql

{

sqlite3_close(db);

}

@end

.h

#import

@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" // 測試用頭文件

#import "ClassMessage.h"

#import "SecViewController.h"

@interface ViewController ()

{

NSMutableArray *array;

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

// 測試用

// 先調用類方法,再通過類方法調用實例方法

//[[SqlData initData] initSql];

// 標題

self.title = @"數據庫";

// 表格行高

self.tableView.rowHeight = 150;

// 初始化數組

array = [NSMutableArray array];

// 跳轉按鈕

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(tiaozhuan)];

}

// 實現跳轉按鈕點擊事件

-(void)tiaozhuan

{

// 創(chuàng)建下一個頁面的主頁面

SecViewController *secVC = [[SecViewController alloc] init];

// 執(zhí)行跳轉 -- 左右側滑

[self.navigationController pushViewController:secVC animated:YES];

}

// 視圖將要顯示

-(void)viewWillAppear:(BOOL)animated

{

// 調用數據庫方法

[[SqlData initData] initSql];

// 調用數據庫 查詢方法

array = [[SqlData initData] showAllArr];

// 關閉數據庫

[[SqlData initData] closeSql];

// 刷新表格

[self.tableView reloadData];

}

#pragma mark -

#pragma mark UITableViewDataSource

// 行數

-(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:@""];

}

// 初始化對象

ClassMessage *classMsg = array[indexPath.row];

// 設置內容

cell.textLabel.text = [NSString stringWithFormat:@"%ld\n%@\n%@\n%@\n%@\n%@",classMsg.classid, classMsg.name, classMsg.age, classMsg.sex, classMsg.height, classMsg.weight];

// 自動換行

cell.textLabel.numberOfLines = 0;

// 返回 cell

return cell;

}

// 點擊表格跳轉

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

// 創(chuàng)建下一面的主頁面

SecViewController *secV = [[SecViewController alloc] init];

// 屬性傳值

secV.message = array[indexPath.row];

// 跳轉

[self.navigationController pushViewController:secV animated:YES];

}

// 刪除行

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

[[SqlData initData] initSql];

// 獲取數據庫中的數據 --- 刪除主鍵id

[[SqlData initData] deleteData:[array[indexPath.row] classid]];

// 關閉數據庫

[[SqlData initData] closeSql];

// 刪除數據

[array removeObject:array[indexPath.row]];

// 刷新表格

[self.tableView reloadData];

}

@end

.h

#import

#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;

// 判斷添加標題

if (classView.nameTf.text.length <= 0) {

self.title = @"添加數據";

// 創(chuàng)建添加按鈕

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(didClickAdd)];

}else{

self.title = @"修改數據";

// 創(chuàng)建修改按鈕

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(didClickSave)];

}

}

// 實現 添加按鈕點擊事件

-(void)didClickAdd

{

// 初始化對象

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;

// 調用數據庫方法

[[SqlData initData] initSql];

// 調用添加數據庫方法

[[SqlData initData] addData:classMessage];

// 調用關閉數據庫方法

[[SqlData initData] closeSql];

// 跳轉回上一視圖

[self.navigationController popViewControllerAnimated:YES];

}

//? 實現 修改按鈕點擊事件

-(void)didClickSave

{

// 切記?。?!別初始化數據源類 ***

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;

// 調用數據庫的單例方法

[[SqlData initData] initSql];

[[SqlData initData] changeData:self.message];

[[SqlData initData] closeSql];

// 跳轉回上一視圖

[self.navigationController popViewControllerAnimated:YES];

}

@end

作者:Cyy

鏈接:http://www.itdecent.cn/p/2d4b7835cb73

來源:簡書

著作權歸作者所有。商業(yè)轉載請聯繫作者獲得授權,非商業(yè)轉載請註明出處。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容