码迷,mamicode.com
首页 > 数据库 > 详细

SQLite3 基本使用方法(二)

时间:2014-06-27 14:15:13      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   tar   

 

 

工程目录:

bubuko.com,布布扣

 

 

Singleton.h

//.h

#define single_interface(class) + (class *)shared##class;

//.m
// \ 代表下一行也属于宏
// ##是分隔符
#define single_implementation(class) static class *_instance; + (class *)shared##class {     if (_instance == nil) {         _instance = [[self alloc] init];     }     return _instance; }  + (id)allocWithZone:(NSZone *)zone {     static dispatch_once_t onceToken;     dispatch_once(&onceToken, ^{         _instance = [super allocWithZone:zone];     });     return _instance; }

 

 

MSUserManager.h

#import <Foundation/Foundation.h>
#import "MSUser.h"
#import <sqlite3.h>
#import "Singleton.h"


@interface MSUserManager : NSObject
{
     sqlite3 * m_pDb;
}

single_interface(MSUserManager)



//
-(void) addUser:(MSUser *)user;

//
-(void) deleteUser:(NSInteger)UserId;

//
- (void)updateUser:(MSUser *)user;

//
-(NSMutableArray *)allUser;

@end

 

 

MSUserManager.m

#import "MSUserManager.h"
#import <sqlite3.h>

@implementation MSUserManager   //单例
single_implementation(MSUserManager)



//在初始化方法中完成数据库链接工作
- (id)init
{
    self = [super init];
    
    if (self) {
        
        //1. 创建数据库
        [self openDB];
        //2. 创建数据库表
        [self createTable];
        
        
    }
    
    return self;
}


//打开数据库,如不存在,则创建。
- (void) openDB
{
    //生成存放在沙盒中的数据库完整路径
    NSString * strDocDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString * strDbName = [strDocDir stringByAppendingPathComponent: @"mySqlite3DB.db"];
    
    
    //sqlite3 数据库的链接,基于该链接可以进行数据库操作
    if (SQLITE_OK == sqlite3_open(strDbName.UTF8String, &m_pDb))
    {
        NSLog(@"创建/打开数据库成功!");
    }
    else
    {
        NSLog(@"创建/打开数据库失败!");
    }
}





//创建数据库表
//使用DBMANAGE创建,把生成的代码赋值过来就OK了。
//表名:tbl_User
//IF NOT EXISTS

//IOS 把id设为自增,在添加数据的时候,也要用null站位,不能不写。
- (void) createTable
{
    NSString * strSql = @"CREATE TABLE IF NOT EXISTS tbl_User (Id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,UserName text,UserPass text)";
    
    char * pErrorMsg;
    if (SQLITE_OK ==  sqlite3_exec(m_pDb, strSql.UTF8String, NULL, NULL, &pErrorMsg)) {
        NSLog(@"创建数据表成功!");
    }
    else
    {
        NSLog(@"创建数据表失败!");
    }
    
}



- (void) execSql:(NSString *)sql msg:(NSString*)msg
{
    char * pErrorMsg;
    if (SQLITE_OK ==  sqlite3_exec(m_pDb, sql.UTF8String, NULL, NULL, &pErrorMsg))
    {
        NSLog(@"%@成功!", msg);
    }
    else
    {
        NSLog(@"%@失败 - %s!", msg, pErrorMsg);
    }
}



#pragma mark - 成员方法


//
-(void) addUser:(MSUser *)user
{
    NSString * strSql = [NSString stringWithFormat: @"INSERT INTO tbl_User VALUES (null, ‘%@‘, ‘%@‘)",
                         user.UserName   , user.UserPass];

    [self execSql:strSql msg:@"添加"];
    
}

//
-(void) deleteUser:(NSInteger)UserId
{
    //和增同理
}

//
- (void)updateUser:(MSUser *)user
{
    //和增同理
}

//
-(NSMutableArray *)allUser
{
    NSString * strSql = @"SELECT * FROM tbl_User";
    
    NSMutableArray * arrReturn = nil;
    
    //1. 评估准备SQL语法是否正确
    sqlite3_stmt * pStmt = NULL;
    if (SQLITE_OK == sqlite3_prepare_v2(m_pDb, strSql.UTF8String, -1, &pStmt, NULL))
    {
        arrReturn = [NSMutableArray array];
        
        //2. 如果能正常查询,调用单步执行方法, 依次取得查询结果
        //如果得到一行记录
        while (SQLITE_ROW == sqlite3_step(pStmt))
        {
            //3.获取/显示查询结果
            int nId = sqlite3_column_int(pStmt, 0);
            const unsigned char * pUserName = sqlite3_column_text(pStmt, 1);
            NSString * pUserNameUTF8 = [NSString stringWithUTF8String:(const char *)pUserName];
            const unsigned char * pUserPass = sqlite3_column_text(pStmt, 2);
            NSString * pUserPassUTF8 = [NSString stringWithUTF8String:(const char *)pUserPass];
            
            MSUser * pUser = [MSUser UserWithId:nId name:pUserNameUTF8 pass:pUserPassUTF8];

            [arrReturn addObject:pUser];
        }
    }
    else
    {
        NSLog(@"sql语法错误!");
    }
    //4. 释放句柄
    sqlite3_finalize(pStmt);
    
    return arrReturn;
}




@end

 

 

 

MSUser.h

#import <Foundation/Foundation.h>

@interface MSUser : NSObject


//工厂方法

//return User信息
+(id) UserWithId:(NSInteger)nId name:(NSString *)strUserName pass:(NSString *)strUserPass;


@property (assign , nonatomic) NSInteger Id;
@property (strong , nonatomic) NSString * UserName;
@property (strong , nonatomic) NSString * UserPass;

@end

 

 

MSUser.m

#import "MSUser.h"

@implementation MSUser

+(id) UserWithId:(NSInteger)nId name:(NSString *)strUserName pass:(NSString *)strUserPass
{
    MSUser * pUser = [[MSUser alloc] init];
    pUser.Id = nId;
    pUser.UserName = strUserName;
    pUser.UserPass = strUserPass;
    return pUser;
}


//
- (NSString *)description
{
    return [NSString stringWithFormat:@"< MSUser:%p  Id:%i  UserName:(%@)  UserPass:(%@) >",
           self, _Id, _UserName, _UserPass];
}

@end

 

MSViewController.m

#import "MSViewController.h"
#import "MSUserManager.h"
#import "MSUser.h"

@interface MSViewController ()

@end

@implementation MSViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    m_arrUser = [[MSUserManager sharedMSUserManager] allUser];
    NSLog(@"%@", m_arrUser);
    
}


@end

 

 

 

  

总结:

  1. 分层结构比较清晰, Model(User) -- Service(UserManager) -- Controller 。 有木有 像三层架构 呢。。。

  2. 单例类,需要理解! 有什么好处?特点?

 

 

 

 

 

 

 

 

 

 

 

 

 

SQLite3 基本使用方法(二),布布扣,bubuko.com

SQLite3 基本使用方法(二)

标签:des   style   class   blog   code   tar   

原文地址:http://www.cnblogs.com/iCodePhone/p/3810575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!