数据库,单例的使用

数据库的使用,和单例的使用

MainViewController.m


#import "MainViewController.h"
#import "DataBaseHandler.h"
@interface MainViewController ()
@end
@implementation MainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor cyanColor];
    //数据库的使用
    
    //使用单例方法
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end

DataBaseHandler.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "Student.h"
//对所有数据库的操作都在这个类中处理
//把这个类写成单例类(在一个应用程序中,只会产生一个对象)
@interface DataBaseHandler : NSObject
{
    //创建一个数据指针,指向本地的数据库文件
    sqlite3 *dbPoint;
}
//单例方法
+ (DataBaseHandler *)shareInstance;
//在进行数据库的增删改查操作之前,需要打开数据库(dbPoint跟本地的数据库文件连接起来)
- (void)openDB;
- (void)closeDB;
//创建表
- (void)createTable;
//添加
- (void)insertStudent:(Student *)student;
//查询
- (NSArray *)selectAllStudents;
@end

DataBaseHandler.m

#import "DataBaseHandler.h"
@implementation DataBaseHandler
+ (DataBaseHandler *)shareInstance
{
    //static 一个应用程序执行期间,只会执行一次
    static DataBaseHandler *dbHandler = nil;
    
    if (dbHandler == nil) {
        //如果指针指向空地址,就创建一个对象
        
        dbHandler = [[DataBaseHandler alloc] init];
        [dbHandler openDB];
        [dbHandler createTable];
        
    }
    return dbHandler;
    
    
    
}
- (void)openDB
{
    //打开数据库的函数
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    //拼接一个数据库的文件路径
    NSString *dbPath = [docPath stringByAppendingPathComponent:@"dataBase.db"];
    
    
    //参数1:数据库文件的路径    参数2:数据库指针的地址
   int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    
    //SQLITE_OK查看错误信息
    NSLog(@"%d", result);
    NSLog(@"%@", dbPath);
    
    
}
- (void)closeDB
{
    sqlite3_close(dbPoint);
}
- (void)createTable
{
    //执行SQL语句的函数
    
    NSString *sql = [NSString stringWithFormat:@"create table student (name text, id integer primary key, age float)"];
    
    //参数1:数据库的指针
    //参数2:要执行的sql语句
    //参数3:
    //参数4:
    //参数5:
    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
    NSLog(@"创建结果%d", result);
}
- (void)insertStudent:(Student *)student
{
    NSString *sql = [NSString stringWithFormat:@"insert into student values(‘%@‘, %d, %f)",student.name,student.number, student.age];
    
    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
    NSLog(@"执行结果%d", result);
}
- (NSArray *)selectAllStudents
{
    //1.创建一个数据库指针的替身
    //替身作为一个临时的数据库指针,保存所有对数据库的操作,最终确认无误后写入本地数据库
    sqlite3_stmt *stmt = nil;
    
    
    NSString *sql = [NSString stringWithFormat:@"select * from student"];
    //2.检查sql语句,准备执行
    //作用:把替身和数据库指针连接起来
    //参数1:数据库指针
    //参数2:sql语句
    //参数3:闲置sql语句的长度 (-1)为不限制
    //参数4:替身的指针
    int result = sqlite3_prepare_v2(dbPoint, [sql UTF8String], -1, &stmt, NULL);
    
    //对sql语句的检查结果进行判断
    if (result == SQLITE_OK) {
        NSMutableArray *array = [NSMutableArray array];
        
        //如果当符合SQL语句查询条件的结果有多行,就执行循环体的代码
        while (sqlite3_setp(stmt) == SQLITE_ROW) {
            //参数1:替身  参数2:取得是第几列的值
           const unsigned char* nameStr = sqlite3_column_text(stmt, 0);
            NSString *name = [NSString stringWithUTF8String:(const char*)nameStr];
            //把拿到的nsstring数据给一个学生对象赋值
            Student *stu = [[Student alloc] init];
            stu.name = name;
            
            stu.number = sqlite3_column_int(stmt, 1);
            stu.age = sqlite3_column_double(stmt, 2);
            //把创建好的学生对象添加到数据中
            [array addObject:stu];
            [stu release];
        }
        
        //释放替身的内存占用,将替身的所有操作应用到底层数据库文件
        sqlite3_finalize(stmt);
        return array;
    }
    
    //如果失败,返回空值
    sqlite3_finalize(stmt);
    return nil;
 
}
@end


Student.h

#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic , retain)NSString *name;
@property (nonatomic , assign)NSInteger number;
@property (nonatomic , assign)float age;
@end

Student.m


#import "Student.h"
@implementation Student
- (void)dealloc
{
    [_name release];
    [super dealloc];
}
@end



本文出自 “小刘_Blog” 博客,请务必保留此出处http://liuyafang.blog.51cto.com/8837978/1557038

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。