美文网首页
SQL数据库简单使用

SQL数据库简单使用

作者: 往日的时光 | 来源:发表于2017-09-09 10:12 被阅读0次

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

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

相关文章

网友评论

      本文标题:SQL数据库简单使用

      本文链接:https://www.haomeiwen.com/subject/xsdojxtx.html