iOS——SQLite數據庫增刪改查demo


開始使用SQLite所需要的幾個步驟

1.需要導入的框架:libsqlite3.0.tbd

2.創建Model類LoL繼承于NSObject用來定義英雄屬性

LoL.h//復制的話注意類名

#import <Foundation/Foundation.h>

@interfaceLoL :NSObject

//編號(主鍵)

@property(nonatomic,assign)NSInteger ids;

//英雄名稱和技能

@property(nonatomic,strong)NSString*name,*skill;

@end

3.創建業務處理類LoadData繼承自NSObject

LoadData.h文件

#import <Foundation/Foundation.h>

#import <sqlite3.h>//導入庫頭文件

#import "LoL.h"http://導入自定義類頭文件

@interfaceLoadData :NSObject {

//數據庫指針

sqlite3*sqliteDB;

}

//單例類

+(instancetype)shareLoadData;

//初始化數據庫

-(void)initDB;

//初始化表格

-(void)initTable;

//添加數據

-(void)addLoLData:(LoL*)lol;

//修改數據

-(void)updateData:(LoL*)lol;

//刪除數據

-(void)deleteData:(NSInteger)ids;

//查詢數據

-(NSMutableArray*)showAllData;

//關閉數據庫

-(void)closeDB;

@end

LoadData.m文件

#import"LoadData.h"

@interface LoadData()<NSCopying>{

}

@end

static LoadData*load;

@implementationLoadData

//單例類

+(instancetype)shareLoadData{

if(!load) {

load= [[LoadData alloc]init];

}

return load;

}

// alloc底層實際調用allocWithZone:

+(instancetype)allocWithZone:(struct _NSZone*)zone{

if(!load) {

load= [super allocWithZone:zone];

}

return load;

}

-(id)copyWithZone:(NSZone*)zone{

return load;

}

//初始化數據庫

-(void)initDB{

//獲得沙盒路徑NSHomeDirectory() docoment沙河目錄

NSString* path =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];// .../document/bys.db

//拼接db文件路徑

NSString*pathSting = [path stringByAppendingString:@"/bys.db"];

//NSString *pathString=[path stringByAppendingPathComponent:@"zw.db"];

NSLog(@"%@",path);

//打開數據庫//轉化字符串[pathSting UTF8String]

//系統自動判斷如果有bys.db文件直接打開如果沒有則創建后打開

int result = sqlite3_open([pathSting UTF8String], &sqliteDB);

if(result ==SQLITE_OK) {

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

//初始化表

[self initTable];

}else{

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

}

}

//初始化表格

-(void)initTable{

//sql語句

// create table是關鍵字不可修改,lol表名可以修改primary key主鍵

const char*sql =

"create table lol(ids integer primary key,names text,skill text)";

//定義一個預編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個參數數據庫指針

//第二個參數sql語句

//第三個參數sql語句的長度-1的話自動匹配長度

//第四個參數預編譯指針

//第五個參數未使用參數

//主要作用是將sql語句編譯到stmt指針中

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

//執行sql語句

int result = sqlite3_step(stmt);

/////////

///可以不寫

if(result == SQLITE_DONE) {

NSLog(@"表創建成功");

}

//銷毀預編譯指針

sqlite3_finalize(stmt);

}

//添加數據

-(void)addLoLData:(LoL*)lol{

//sql語句?是占位符

//"lol(ids integer primary key,names text,skill text)";

//LoL *l = [[LoL alloc]init];

//l.name= add.nameTF.text;

//l.skill = add.skillTF.text;

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

//定義一個預編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個參數數據庫指針

//第二個參數sql語句

//第三個參數sql語句的長度-1的話自動匹配長度

//第四個參數預編譯指針

//第五個參數未使用參數

//主要作用是將sql語句編譯到stmt指針中

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

//設置綁定符

//第一個參數預編譯指針

//第二個參數綁定第幾個問號

//第三個參數綁定的變量的長度

//第四個參數將字符串轉換成sql語句識別的text類型

sqlite3_bind_text(stmt,1, [lol.name UTF8String], -1,SQLITE_TRANSIENT);

sqlite3_bind_text(stmt,2, [lol.skill UTF8String], -1,SQLITE_TRANSIENT);

//執行sql語句

sqlite3_step(stmt);

//銷毀預編譯指針

sqlite3_finalize(stmt);

}

//修改數據

-(void)updateData:(LoL*)lol{

//sql語句?是

const char*sql ="update lol set names=? , skill=? where ids=?";

//定義一個預編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個參數數據庫指針

//第二個參數sql語句

//第三個參數sql語句的長度-1的話自動匹配長度

//第四個參數預編譯指針

//第五個參數未使用參數

//主要作用是將sql語句編譯到stmt指針中

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

//設置綁定符

//第一個參數預編譯指針

//第二個參數綁定第幾個問號

//第三個參數綁定的變量的長度

//第四個參數將字符串轉換成sql語句識別的text類型

sqlite3_bind_text(stmt,1, [lol.name UTF8String], -1,SQLITE_TRANSIENT);

sqlite3_bind_text(stmt,2, [lol.skill UTF8String], -1,SQLITE_TRANSIENT);

sqlite3_bind_int(stmt,3, (int)lol.ids);

NSLog(@"%s",sqlite3_errmsg(sqliteDB));

//執行sql語句

sqlite3_step(stmt);

//銷毀預編譯指針

sqlite3_finalize(stmt);

}

//刪除數據

-(void)deleteData:(NSInteger)ids{

//sql語句?是

const char*sql ="delete from lol where ids=?";

//定義一個預編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個參數數據庫指針

//第二個參數sql語句

//第三個參數sql語句的長度-1的話自動匹配長度

//第四個參數預編譯指針

//第五個參數未使用參數

//主要作用是將sql語句編譯到stmt指針中

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

//設置綁定符

//第一個參數預編譯指針

//第二個參數綁定第幾個問號

//第三個參數綁定的變量的長度

//第四個參數將字符串轉換成sql語句識別的text類型

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

//執行sql語句

sqlite3_step(stmt);

//銷毀預編譯指針

sqlite3_finalize(stmt);

}

//查詢數據

-(NSMutableArray*)showAllData{

//sql語句?是

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

//定義一個預編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個參數數據庫指針

//第二個參數sql語句

//第三個參數sql語句的長度-1的話自動匹配長度

//第四個參數預編譯指針

//第五個參數未使用參數

//主要作用是將sql語句編譯到stmt指針中

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

//存放查詢之后的所有數據

NSMutableArray*arr = [[NSMutableArray alloc]init];

//執行sql語句

while(sqlite3_step(stmt) ==SQLITE_ROW) {

LoL*l = [[LoL alloc]init];

//獲得字段的數據下標是從0開始的

//第2個參數是獲得第幾個字段的值

l.ids=sqlite3_column_int(stmt,0);

//如果是文本類型則返回的c的字符串需要轉換NSString

l.name=[NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt,1)];

l.skill=[NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt,2)];

[arr addObject:l];

}

;

//銷毀預編譯指針

sqlite3_finalize(stmt);

return arr ;

}

//關閉數據庫

-(void)closeDB{

sqlite3_close(sqliteDB);

}

@end

3.創建視圖AddView繼承自UIView

AddView.h

//AddView.h

#import <UIKit/UIKit.h>

@interfaceAddView :UIView

@property(nonatomic,strong)UITextField*nameTF,*skillTF;

@property(nonatomic,strong)UIButton*btn;

@end

AddView.m

//AddView.m

//

#import"AddView.h"

@implementation AddView

-(UITextField*)nameTF{

if(!_nameTF) {

_nameTF= [[UITextField alloc]initWithFrame:CGRectMake(100,100,200,44)];

_nameTF.placeholder=@"英雄名稱";

_nameTF.backgroundColor= [UIColor lightGrayColor];

}

return _nameTF;

}

-(UITextField*)skillTF{

if(!_skillTF) {

_skillTF= [[UITextField alloc]initWithFrame:CGRectMake(100,200,200,44)];

_skillTF.placeholder=@"英雄技能";

_skillTF.backgroundColor= [UIColor lightGrayColor];

}

return _skillTF;

}

-(UIButton*)btn{

if(!_btn) {

_btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];

_btn.frame=CGRectMake(100,300,200,44);

_btn.backgroundColor= [UIColor orangeColor];

[_btn setTitle:@"添加數據"forState:UIControlStateNormal];

}

return _btn;

}

-(instancetype)initWithFrame:(CGRect)frame{

self.backgroundColor= [UIColor whiteColor];

if(self= [super initWithFrame:frame]) {

[self addSubview:self.nameTF];

[self addSubview:self.skillTF];

[self addSubview:self.btn];

}

return self;

}

@end

4.在APPDelegate中添加導航控制器ViewController為根視圖

5.ViewController.m

#import"ViewController.h"

#import"LoadData.h"

#import"LoL.h"

#import"AddViewController.h"

#import"UpDateViewController.h"

@interface ViewController()<UITableViewDataSource,UITableViewDelegate>{

UITableView*table;

NSMutableArray*arr;

}

@end

@implementationViewController

- (void)viewDidLoad {

[superviewDidLoad];

self.navigationItem.title=@"英雄聯盟";

UIBarButtonItem*item = [[UIBarButtonItem alloc]initWithTitle:@"添加英雄"style:UIBarButtonItemStylePlain target:self action:@selector(click)];

self.navigationItem.rightBarButtonItem= item;

table= [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];

table.dataSource=self;

table.delegate=self;

table.rowHeight=100;

[self.view addSubview:table];

}

-(void)click{

AddViewController*add = [[AddViewController alloc]init];

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

}

-(void)viewWillAppear:(BOOL)animated{

//打開數據庫

[[LoadData shareLoadData]initDB];

//獲得數據庫數據

arr= [[LoadData shareLoadData]showAllData];

//關閉數據庫

[[LoadData shareLoadData]closeDB];

[table reloadData];

}

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{

return arr.count;

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

static NSString*cellId =@"cellid";

UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:cellId];

if(!cell) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuse Identifier:cellId];

}

LoL*l = [arr objectAtIndex:indexPath.row];

cell.textLabel.text= [NSString stringWithFormat:@"%ld\n%@\n%@",l.ids,l.name,l.skill];

cell.textLabel.numberOfLines=0;

return cell;

}

-(BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath{

return YES;

}

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

if(editingStyle ==UITableViewCellEditingStyleDelete){

//先刪除數據庫對應數據

[[LoadData shareLoadData]initDB];

[[LoadData shareLoadData]deleteData:[arr[indexPath.row]ids]];

[[LoadData shareLoadData]closeDB];

//在刪除arr數據

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

//刷新表格

[table reloadData];

}

}

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

UpDateViewController*up = [[UpDateViewController alloc]init];

up.ls=arr[indexPath.row];

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

}

@end

6.創建添加視圖界面AddViewController繼承自UIViewController

AddViewController.m文件

#import"AddViewController.h"

#import"AddView.h"

#import"LoadData.h"

#import"LoL.h"

@interface AddViewController(){

AddView*add;

}

@end

@implementation AddViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor= [UIColor whiteColor];

add= [[AddView alloc]initWithFrame:self.view.frame];

[self.view addSubview:add];

[add.btn addTarget:self action:@selector(click)forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.title=@"添加英雄";

}

-(void)click{

LoL*l = [[LoL alloc]init];

l.name=add.nameTF.text;

l.skill=add.skillTF.text;

//打開數據庫

[[LoadData shareLoadData]initDB];

//添加數據

[[LoadData shareLoadData]addLoLData:l];

//關閉數據庫

[[LoadData shareLoadData]closeDB];

[self.navigationController popViewControllerAnimated:YES];

}

@end

7.創建修改視圖界面UpDateViewController繼承自UIViewController

UpDateViewController.h文件

#import <UIKit/UIKit.h>

#import "AddView.h"

#import "LoL.h"

@interface UpDateViewController :UIViewController

@property(nonatomic,strong)LoL*ls;

@end

UpDateViewController.m文件

#import"UpDateViewController.h"

#import"LoadData.h"

@interface UpDateViewController(){

AddView*update;

}

@end

@implementation UpDateViewController

- (void)viewDidLoad {

[superviewDidLoad];

self.view.backgroundColor= [UIColor whiteColor];

update= [[AddView alloc]initWithFrame:self.view.frame];

[self.view addSubview:update];

[update.btn addTarget:self action:@selector(click)forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.title=@"修改英雄";

update.nameTF.text=self.ls.name;

update.skillTF.text=self.ls.skill;

}

-(void)click{

LoL*l = [[LoL alloc]init];

l.ids=self.ls.ids;

l.name=update.nameTF.text;

l.skill=update.skillTF.text;

//打開數據庫

[[LoadData shareLoadData]initDB];

//添加數據

[[LoadData shareLoadData]updateData:l];

//關閉數據庫

[[LoadData shareLoadData]closeDB];

[self.navigationController popViewControllerAnimated:YES];

}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內容