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"//导入自定义类头文件

@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阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容