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"

// 创建一个静态变量

static SqlData *sqlData;

@implementation SqlData

// 单例方法 *** --- 采用类方法

+(instancetype)initData

{

// 判断,如果没有创建静态变量,就创建

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:如果是这个状态,表示数据库打开成功

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

// 创建表格时,如果没有执行 exists 就进行创建

// const 常量 -- 不能发生改变的量 --- ""引号中不可以使用中文 --- 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);

// 执行预编译接口 -- step:执行

//    sqlite3_step(stmt);

// 判断 一行一行的去判断是否执行完成

if (sqlite3_step(stmt) == SQLITE_DONE) {

NSLog(@"数据库表格创建成功");

}else{

NSLog(@"数据库表格创建失败");

}

// 销毁接口 -- 防止有空指针和野指针,造成程序崩溃

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

// 执行预编译接口 -- step:执行

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

// 执行预编译接口 -- step:执行

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

// 执行预编译接口 -- step:执行

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

// 所有的数组都是以数组的形式存储的

// 创建数组

NSMutableArray *arr = [NSMutableArray array];

// 执行数据库中的预编译接口  ----- 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

{

// 创建下一个页面的主页面

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

// 执行跳转 -- 左右侧滑

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

// 如果找不到就创建 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

{

// 创建下一面的主页面

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 = @"添加数据";

// 创建添加按钮

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

}else{

self.title = @"修改数据";

// 创建修改按钮

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.jianshu.com/p/2d4b7835cb73

來源:簡書

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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

推荐阅读更多精彩内容