iOS——SQLite數(shù)據(jù)庫(kù)增刪改查demo


開始使用SQLite所需要的幾個(gè)步驟

1.需要導(dǎo)入的框架:libsqlite3.0.tbd

2.創(chuàng)建Model類LoL繼承于NSObject用來定義英雄屬性

LoL.h//復(fù)制的話注意類名

#import <Foundation/Foundation.h>

@interfaceLoL :NSObject

//編號(hào)(主鍵)

@property(nonatomic,assign)NSInteger ids;

//英雄名稱和技能

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

@end

3.創(chuàng)建業(yè)務(wù)處理類LoadData繼承自NSObject

LoadData.h文件

#import <Foundation/Foundation.h>

#import <sqlite3.h>//導(dǎo)入庫(kù)頭文件

#import "LoL.h"http://導(dǎo)入自定義類頭文件

@interfaceLoadData :NSObject {

//數(shù)據(jù)庫(kù)指針

sqlite3*sqliteDB;

}

//單例類

+(instancetype)shareLoadData;

//初始化數(shù)據(jù)庫(kù)

-(void)initDB;

//初始化表格

-(void)initTable;

//添加數(shù)據(jù)

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

//修改數(shù)據(jù)

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

//刪除數(shù)據(jù)

-(void)deleteData:(NSInteger)ids;

//查詢數(shù)據(jù)

-(NSMutableArray*)showAllData;

//關(guān)閉數(shù)據(jù)庫(kù)

-(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底層實(shí)際調(diào)用allocWithZone:

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

if(!load) {

load= [super allocWithZone:zone];

}

return load;

}

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

return load;

}

//初始化數(shù)據(jù)庫(kù)

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

//打開數(shù)據(jù)庫(kù)//轉(zhuǎn)化字符串[pathSting UTF8String]

//系統(tǒng)自動(dòng)判斷如果有bys.db文件直接打開如果沒有則創(chuàng)建后打開

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

if(result ==SQLITE_OK) {

NSLog(@"數(shù)據(jù)庫(kù)打開成功");

//初始化表

[self initTable];

}else{

NSLog(@"數(shù)據(jù)庫(kù)打開失敗");

}

}

//初始化表格

-(void)initTable{

//sql語句

// create table是關(guān)鍵字不可修改,lol表名可以修改primary key主鍵

const char*sql =

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

//定義一個(gè)預(yù)編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個(gè)參數(shù)數(shù)據(jù)庫(kù)指針

//第二個(gè)參數(shù)sql語句

//第三個(gè)參數(shù)sql語句的長(zhǎng)度-1的話自動(dòng)匹配長(zhǎng)度

//第四個(gè)參數(shù)預(yù)編譯指針

//第五個(gè)參數(shù)未使用參數(shù)

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

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

//執(zhí)行sql語句

int result = sqlite3_step(stmt);

/////////

///可以不寫

if(result == SQLITE_DONE) {

NSLog(@"表創(chuàng)建成功");

}

//銷毀預(yù)編譯指針

sqlite3_finalize(stmt);

}

//添加數(shù)據(jù)

-(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,?,?)";

//定義一個(gè)預(yù)編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個(gè)參數(shù)數(shù)據(jù)庫(kù)指針

//第二個(gè)參數(shù)sql語句

//第三個(gè)參數(shù)sql語句的長(zhǎng)度-1的話自動(dòng)匹配長(zhǎng)度

//第四個(gè)參數(shù)預(yù)編譯指針

//第五個(gè)參數(shù)未使用參數(shù)

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

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

//設(shè)置綁定符

//第一個(gè)參數(shù)預(yù)編譯指針

//第二個(gè)參數(shù)綁定第幾個(gè)問號(hào)

//第三個(gè)參數(shù)綁定的變量的長(zhǎng)度

//第四個(gè)參數(shù)將字符串轉(zhuǎn)換成sql語句識(shí)別的text類型

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

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

//執(zhí)行sql語句

sqlite3_step(stmt);

//銷毀預(yù)編譯指針

sqlite3_finalize(stmt);

}

//修改數(shù)據(jù)

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

//sql語句?是

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

//定義一個(gè)預(yù)編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個(gè)參數(shù)數(shù)據(jù)庫(kù)指針

//第二個(gè)參數(shù)sql語句

//第三個(gè)參數(shù)sql語句的長(zhǎng)度-1的話自動(dòng)匹配長(zhǎng)度

//第四個(gè)參數(shù)預(yù)編譯指針

//第五個(gè)參數(shù)未使用參數(shù)

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

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

//設(shè)置綁定符

//第一個(gè)參數(shù)預(yù)編譯指針

//第二個(gè)參數(shù)綁定第幾個(gè)問號(hào)

//第三個(gè)參數(shù)綁定的變量的長(zhǎng)度

//第四個(gè)參數(shù)將字符串轉(zhuǎn)換成sql語句識(shí)別的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));

//執(zhí)行sql語句

sqlite3_step(stmt);

//銷毀預(yù)編譯指針

sqlite3_finalize(stmt);

}

//刪除數(shù)據(jù)

-(void)deleteData:(NSInteger)ids{

//sql語句?是

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

//定義一個(gè)預(yù)編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個(gè)參數(shù)數(shù)據(jù)庫(kù)指針

//第二個(gè)參數(shù)sql語句

//第三個(gè)參數(shù)sql語句的長(zhǎng)度-1的話自動(dòng)匹配長(zhǎng)度

//第四個(gè)參數(shù)預(yù)編譯指針

//第五個(gè)參數(shù)未使用參數(shù)

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

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

//設(shè)置綁定符

//第一個(gè)參數(shù)預(yù)編譯指針

//第二個(gè)參數(shù)綁定第幾個(gè)問號(hào)

//第三個(gè)參數(shù)綁定的變量的長(zhǎng)度

//第四個(gè)參數(shù)將字符串轉(zhuǎn)換成sql語句識(shí)別的text類型

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

//執(zhí)行sql語句

sqlite3_step(stmt);

//銷毀預(yù)編譯指針

sqlite3_finalize(stmt);

}

//查詢數(shù)據(jù)

-(NSMutableArray*)showAllData{

//sql語句?是

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

//定義一個(gè)預(yù)編譯指針

sqlite3_stmt*stmt;

//編譯sql語句

//第一個(gè)參數(shù)數(shù)據(jù)庫(kù)指針

//第二個(gè)參數(shù)sql語句

//第三個(gè)參數(shù)sql語句的長(zhǎng)度-1的話自動(dòng)匹配長(zhǎng)度

//第四個(gè)參數(shù)預(yù)編譯指針

//第五個(gè)參數(shù)未使用參數(shù)

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

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

//存放查詢之后的所有數(shù)據(jù)

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

//執(zhí)行sql語句

while(sqlite3_step(stmt) ==SQLITE_ROW) {

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

//獲得字段的數(shù)據(jù)下標(biāo)是從0開始的

//第2個(gè)參數(shù)是獲得第幾個(gè)字段的值

l.ids=sqlite3_column_int(stmt,0);

//如果是文本類型則返回的c的字符串需要轉(zhuǎn)換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];

}

;

//銷毀預(yù)編譯指針

sqlite3_finalize(stmt);

return arr ;

}

//關(guān)閉數(shù)據(jù)庫(kù)

-(void)closeDB{

sqlite3_close(sqliteDB);

}

@end

3.創(chuàng)建視圖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:@"添加數(shù)據(jù)"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中添加導(dǎo)航控制器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=@"英雄聯(lián)盟";

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{

//打開數(shù)據(jù)庫(kù)

[[LoadData shareLoadData]initDB];

//獲得數(shù)據(jù)庫(kù)數(shù)據(jù)

arr= [[LoadData shareLoadData]showAllData];

//關(guān)閉數(shù)據(jù)庫(kù)

[[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){

//先刪除數(shù)據(jù)庫(kù)對(duì)應(yīng)數(shù)據(jù)

[[LoadData shareLoadData]initDB];

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

[[LoadData shareLoadData]closeDB];

//在刪除arr數(shù)據(jù)

[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.創(chuàng)建添加視圖界面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;

//打開數(shù)據(jù)庫(kù)

[[LoadData shareLoadData]initDB];

//添加數(shù)據(jù)

[[LoadData shareLoadData]addLoLData:l];

//關(guān)閉數(shù)據(jù)庫(kù)

[[LoadData shareLoadData]closeDB];

[self.navigationController popViewControllerAnimated:YES];

}

@end

7.創(chuàng)建修改視圖界面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;

//打開數(shù)據(jù)庫(kù)

[[LoadData shareLoadData]initDB];

//添加數(shù)據(jù)

[[LoadData shareLoadData]updateData:l];

//關(guān)閉數(shù)據(jù)庫(kù)

[[LoadData shareLoadData]closeDB];

[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)容