SQL数据库简单使用

1:什么是SQLite?

SQLite是一款轻型的嵌入式关系数据库
它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了
目前广泛应用于移动设备中存储数据(Android/iOS)
处理数据的速度非常快,效率非常高

2:什么是数据库?

数据库(Database)是按照数据结构来组织、存储和管理数据的仓库(类似于excel表格)
数据库可以分为2大种类(了解)
关系型数据库(主流)
对象型数据库

首先看一下Demo,增删改查功能:

sqlite3.gif

有了基本了解之后我们就创建一个项目
首先我们把sqlite3的依赖库导入

导入sqlite3框架

然后我们就用MVC格式先创建好所用到的类

我们所需要用到的类

首先我们在model里面创建的ClassRoom.h用来存放我们的属性和主键,代码如下:

// 主键值
@property(nonatomic,assign)NSInteger integer;
// 姓名和年龄属性
@property(nonatomic,strong)NSString *name,*age;
  • 什么是主键?
    主键就是相当于身份证一样,用来区分每一条数据
  • 为什么需要主键?
    如果数据表中就name和age两个字段,而且有些记录的name和age字段的值都一样时,那么就没有办法区分这些数据,造成了数据库的记录不唯一,不方便管理数据.
    良好的数据库编程规范应该要保证每条数据的唯一性,为此,增加了主键的约束.
    也就是说,每张表都必须有一个主键,用来标识记录的唯一性.

然后我们就在LoadData.h里面写我们所用到的方法,代码如下:

#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "ClassRoom.h"
@interface LoadData : NSObject
{
    sqlite3 *DB;
}

// 单例
+(instancetype)shardData;
// 初始化数据库
-(void)initData;
// 创建数据库表格
-(void)createtable;
// 关闭数据库
-(void)closeDataBase;
// 添加数据
-(void)addData:(ClassRoom *)thaData;
// 删除数据
-(void)deleteData:(NSInteger)theId;
// 修改数据
-(void)changeData:(ClassRoom *)theData;
// 查询数据
-(NSMutableArray *)dataArray;

@end

LoadData.m里面我们就要用这些来写增删改查的方法,这里是最重要的部分,首先我们生成一个路径,然后创建一个数据库,创建一个表,然后就是增删改查,而且SQL语句使我们所需要记住的,demo里的注释写的很详细,大家可以看注释:

#import "LoadData.h"

// 单例对象
static LoadData *ld = nil;
@implementation LoadData

// 单例
+(instancetype)shardData
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ld = [[LoadData alloc]init];
    });
    return ld;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (!ld)
    {
        ld = [super allocWithZone:zone];
    }
    return ld;
}

-(id)copy
{
    return self;
}

-(id)mutableCopy
{
    return self;
}

// 初始化数据库
-(void)initData
{
    // 创建Docmuent目录
    NSString *strPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    // 拼接数据库的表名的路径
    NSString *strName = [strPath stringByAppendingString:@"/1509E.db"];
    
    if (sqlite3_open([strName UTF8String], &DB)==SQLITE_OK)
    {
        NSLog(@"打开是成功的");
        
        [self createtable];
    }else
    {
        NSLog(@"打开失败");
    }
}
// 创建数据库表格
-(void)createtable
{
    
    // 创建sql语句,格式:create table if not exists 表名(主键 id integer primary key,加上所有用到的数据)
    
    const char *sql = "create table if not exists classroom(inTeger integer primary key,name text,age text)";
    
    // 预编译指针
    sqlite3_stmt *stmt;
    // 绑定预编译指针
    sqlite3_prepare_v2(DB, sql, -1, &stmt, nil);
    
    // 执行预编译指针
    if (sqlite3_step(stmt) == SQLITE_DONE)
    {
        NSLog(@"表格创建成功");
    }else
    {
        NSLog(@"表格创建失败");
    }
    
}



// 添加数据
-(void)addData:(ClassRoom *)thaData
{
    
    // 格式:insert into 表名 values(null,添加的数据?,?)
    
    const char *sql = "insert into classroom values(null,?,?)";
    
    // 预编译指针
    sqlite3_stmt *stmt;
    // 绑定预编译指针
    sqlite3_prepare_v2(DB, sql, -1, &stmt, nil);
    // 绑定占位符
    sqlite3_bind_text(stmt, 1, [thaData.name UTF8String], -1, SQLITE_TRANSIENT);
    // 绑定占位符
    sqlite3_bind_text(stmt, 2, [thaData.age UTF8String], -1, SQLITE_TRANSIENT);
    // 执行预编译指针
    sqlite3_step(stmt);
    // 销毁预编译指针
    sqlite3_finalize(stmt);
    
    
}
// 删除数据
-(void)deleteData:(NSInteger)theId
{
    
    // 格式:delete from 表名 where 表格的主键名:id = ?
    const char *sql = "delete from classroom where inTeger = ?";
    
    // 预编译指针
    sqlite3_stmt *stmt;
    // 绑定预编译指针
    sqlite3_prepare_v2(DB, sql, -1, &stmt, nil);
    // 绑定占位符
    sqlite3_bind_int(stmt, 1, (int)theId);
    // 执行预编译指针
    sqlite3_step(stmt);
    // 销毁预编译指针
    sqlite3_finalize(stmt);
    
}
// 修改数据
-(void)changeData:(ClassRoom *)theData
{
    
    // 格式:update 表名 set 数据类型 where 主键id
    const char *sql = "update classroom set name = ?,age = ? where inTeger = ?";
    
    // 预编译指针
    sqlite3_stmt *stmt;
    // 绑定预编译指针
    sqlite3_prepare_v2(DB, sql, -1, &stmt, nil);
    // 绑定占位符
    sqlite3_bind_text(stmt, 1, [theData.name UTF8String], -1, SQLITE_TRANSIENT);
    
    sqlite3_bind_text(stmt, 2, [theData.age UTF8String], -1, SQLITE_TRANSIENT);
    
    // 绑定主键integer
    sqlite3_bind_int(stmt, 3, (int)theData.integer);
    
    // 执行预编译指针
    sqlite3_step(stmt);
    // 销毁预编译指针
    sqlite3_finalize(stmt);
    
}
// 查询数据
-(NSMutableArray *)dataArray
{
   // 格式:select *from 表名
    const char *sql = "select *from classroom";
    
    // 预编译指针
    sqlite3_stmt *stmt;
    // 绑定预编译指针
    sqlite3_prepare_v2(DB, sql, -1, &stmt, nil);
    
    NSMutableArray *arr = [NSMutableArray array];
    
    while (sqlite3_step(stmt) == SQLITE_ROW)
    {
        ClassRoom *room = [[ClassRoom alloc]init];
        
        room.integer = sqlite3_column_int(stmt, 0);
        
        room.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
        
        room.age = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
        
        [arr addObject:room];
    }
    
    // 销毁预编译指针
    sqlite3_finalize(stmt);
    
    return arr;
}

// 关闭数据库
-(void)closeDataBase
{
    sqlite3_close(DB);
}

@end

然后我们在添加的视图ClassView里面添加两个UITextField用来添加数据使用:

#import "ClassView.h"

@implementation ClassView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self addSubview:self.nameTF];
        [self addSubview:self.ageTF];
    }
    return self;
}

-(UITextField *)nameTF
{
    if (!_nameTF)
    {
        _nameTF = [[UITextField alloc]initWithFrame:CGRectMake(30, 100, 200, 44)];
        _nameTF.placeholder = @"请输入姓名";
        _nameTF.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _nameTF;
}

-(UITextField *)ageTF
{
    if (!_ageTF)
    {
        _ageTF = [[UITextField alloc]initWithFrame:CGRectMake(30, 160, 200, 44)];
        _ageTF.placeholder = @"请输入年龄";
        _ageTF.borderStyle = UITextBorderStyleRoundedRect;
        _ageTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _ageTF;
}


@end

接下来就来到我们的控制器里,首先把我们所继承的UIViewController改成UITableViewController,这样省去很多代码,我们再创建一个MyviewController用来第二个页面,然后在viewController.m:

#import "ViewController.h"
#import "LoadData.h"
#import "ClassRoom.h"
#import "MyViewController.h"
@interface ViewController ()
{
    NSMutableArray *array;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(click)];
    
    // 初始化数组
    array = [NSMutableArray new];
    
    
}


// 导航条右按钮点击方法
-(void)click
{
    MyViewController *my = [[MyViewController alloc]init];
    
    [self.navigationController pushViewController:my animated:YES];
}


// 表格

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    }
    ClassRoom *room = array[indexPath.row];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%ld\n%@\n%@",room.integer,room.name,room.age];
    cell.textLabel.numberOfLines = 0;
    
    return cell;
}

// 视图将要出现的方法
-(void)viewWillAppear:(BOOL)animated
{
    // 初始化数据库
    [[LoadData shardData]initData];
    // 将查询出来的数据赋值给数组
    array = [[LoadData shardData]dataArray];
    
    // 关闭数据库
    [[LoadData shardData]closeDataBase];
    // 刷新表格
    [self.tableView reloadData];
}

// 删除数据库
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 初始化数据库
    [[LoadData shardData]initData];
    // 调用数据库里面的删除方法,根据数组下标 找到每一行的主键值
    [[LoadData shardData]deleteData:[array[indexPath.row]integer]];
    // 关闭数据库
    [[LoadData shardData]closeDataBase];
    // 删除单元格内容
    [array removeObject:array[indexPath.row]];
    // 刷新表格
    [self.tableView reloadData];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyViewController *my = [[MyViewController alloc]init];
    
    my.room = array[indexPath.row];
    
    [self.navigationController pushViewController:my animated:YES];
}


@end

在MyviewController.h中创建一个属性传值,用来修改数据使用:

#import <UIKit/UIKit.h>
#import "ClassRoom.h"
@interface MyViewController : UIViewController

// 属性传值,用来接收上一个控制器的内容
@property(nonatomic,strong)ClassRoom *room;

@end

最后在MyviewController.m中:

#import "MyViewController.h"
#import "ClassView.h"
#import "LoadData.h"
@interface MyViewController ()
{
    ClassView *classview;
}
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    classview = [[ClassView alloc]initWithFrame:self.view.frame];
    
    classview.backgroundColor = [UIColor whiteColor];
    
    self.view = classview;
    
    
    classview.nameTF.text = self.room.name;
    classview.ageTF.text = self.room.age;
    
    if (classview.nameTF.text.length<=0)
    {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
    }else
    {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(edit)];
    }
    
}

-(void)save
{
    ClassRoom *room = [[ClassRoom alloc]init];
    
    room.name = classview.nameTF.text;
    room.age = classview.ageTF.text;
    
    [[LoadData shardData]initData];
    
    [[LoadData shardData]addData:room];
    
    [[LoadData shardData]closeDataBase];
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)edit
{
    self.room.name = classview.nameTF.text;
    self.room.age = classview.ageTF.text;
    
    // 初始化数据库
    [[LoadData shardData]initData];
    // 调用数据库修改方法
    [[LoadData shardData]changeData:self.room];
    // 关闭数据库
    [[LoadData shardData]closeDataBase];
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end

最后写的有点匆忙,见谅.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容

  • Realm是由Y Combinator公司孵化出来的一款可以用于iOS(同样适用于Swift&Objective-...
    小歪子go阅读 2,201评论 6 9
  • SQL语言基础 本章,我们将会重点探讨SQL语言基础,学习用SQL进行数据库的基本数据查询操作。另外请注意本章的S...
    厲铆兄阅读 5,292评论 2 46
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,244评论 25 707
  • 日暮疏雨纷纷, 风吹残红落尽。 高山流水缘,过眼已是无痕。 春分。春分。今日惜别故人。
    轻扬时光阅读 202评论 3 3
  • 又陷入了我的周期丧气循环,每次都是一些微不足道的小事像蝴蝶翅膀掀起我心里的狂风巨浪,然后进入自我否定,自我批判...
    dyagnes阅读 107评论 0 0