FMDB使用

用戶信息類:sql

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

//用戶數據信息
@interface UserInfo : NSObject
//用戶名
@property (retain,nonatomic) NSString* mName ;
//用戶ID
@property (retain,nonatomic) NSString* mUserID ;
//年齡
@property (assign,nonatomic) int mAge ;
//郵件
@property (retain,nonatomic) NSString* mEMail ;
//用戶頭像圖像文件
@property (retain,nonatomic) UIImage* mImage ;

@end

#import "UserInfo.h"

@implementation UserInfo

@end

數據庫管理類:數據庫

#import <Foundation/Foundation.h>
#import "UserInfo.h"
//數據庫管理類
@interface FMDBMgr : NSObject
{
    //數據數組
    NSMutableArray* _arrayUsers ;
}
//打開數據庫文件
-(BOOL) openFMDB ;
//將數組寫入到數據庫中
-(void) saveFMDB ;

//插入一條數據到數據庫
-(BOOL) insertUserToDB:(UserInfo*) user ;

//插入數據到內存中
-(void) insertUser:(UserInfo*) user ;

//從數據庫中刪除
-(BOOL) deleteUserFromDB:(UserInfo*) user ;

//從數據內存中刪除
-(void) deleteUser:(UserInfo*) user ;

//更新用戶數據
-(BOOL) updateInDB:(UserInfo*) user ;

//更新數組中的數據
-(BOOL) updateUser:(UserInfo*) user ;

//返回數據庫中的全部用戶數據
-(NSArray*) selectAllFromDB ;
//返回內存數組中的數據
-(NSArray*) getAllUsers ;

@end

#import "FMDBMgr.h"
#import "FMDatabase.h"
/*
 對於FMDB目錄中的這三個文件作下功能描述:
 FMDatabase : 建立SQLite數據庫
 FMResultSet :獲取執行sql查詢後的結果集
 FMDatabaseQueue :在多個線程執行查詢和更新時會使用這個類。
 
 */
@implementation FMDBMgr

-(id) init
{
    self = [super init] ;
    if (self) {
        _arrayUsers = [[NSMutableArray alloc] init] ;
    }
    return self ;
}
// 打開數據庫
-(BOOL) openFMDB
{
    NSString* strPath = [NSHomeDirectory() stringByAppendingString:@"/tmp/FMDB.db"];
    //只要數據庫的路徑地址相同
    //fmdb操做的是同一個數據庫
    FMDatabase* fmdb = [[FMDatabase alloc] initWithPath:strPath] ;
    
    NSString* strCreate = @"create table if not exists UserTB(ID integer primary key autoincrement,Name varchar(128),UserID varchar(128),Age smallint,imagePath varchar(1024));";
    
    BOOL isOpen = [fmdb open] ;
//    [fmdb close];
    BOOL isCreate =  [fmdb executeUpdate:strCreate] ;
    //是否建立成功
    return isCreate;
}

-(void) insertUser:(UserInfo *)user
{
    //添加時,有可能添加多個相同的元素
    [_arrayUsers addObject:user] ;
}

-(void) deleteUser:(UserInfo *)user
{
    //[_arrayUsers removeObject:user] ;
    
    for (int i = 0 ; i < _arrayUsers.count; i++)
    {
        UserInfo* u = _arrayUsers[i] ;
        if ([u.mUserID isEqualToString:user.mUserID])
        {
            [_arrayUsers removeObjectAtIndex:i] ;
        }
    }
}
//更新數據
-(BOOL) updateUser:(UserInfo *)user
{
    BOOL isUpdate = NO ;
    for (int i = 0 ; i < _arrayUsers.count; i++)
    {
        UserInfo* u = _arrayUsers[i] ;
        if ([u.mUserID isEqualToString:user.mUserID])
        {
            isUpdate = YES ;
            
            [_arrayUsers replaceObjectAtIndex:i withObject:user] ;
        }
    }
    return isUpdate ;
}



//插入到數據庫
-(BOOL) insertUserToDB:(UserInfo *)user
{
    BOOL isInsert = NO ;
    
    NSString* strPath = [NSHomeDirectory() stringByAppendingString:@"/tmp/FMDB.db"];
    //只要數據庫的路徑地址相同
    //fmdb操做的是同一個數據庫
    FMDatabase* fmdb = [[FMDatabase alloc] initWithPath:strPath] ;
    
    [fmdb open] ;
    
    //先要查詢數據庫中是否有相同 userID的用戶
    NSString* strQuery = @"select * from UserTB where UserID = ?;";
    
    FMResultSet* set = [fmdb executeQuery:strQuery,user.mUserID] ;
    
    //若是第一條數據沒有結果
    //沒有任何數據
    if ([set next] == NO)
    {
        NSString* strInsert = @"insert into UserTB(Name,UserID,Age,ImagePath)"
        " Values(?,?,?,?);" ;
        
//        user.mImage ;
        
        //將JPG格式的圖片轉化爲NSData二進制格式
        //參數一:image對象指針,內存格式要求爲JPG
        //參數二:將JPG格式轉化爲文件時的壓縮比例
        //比例範圍0~1,值越小,壓縮比越大,文件越小,質量越低
        //值越大,壓縮比越低,文件越大,質量越高
        
        //返回值時轉化過的數據文件
        //若是格式不正確:返回值爲nil
        NSData* iData = UIImageJPEGRepresentation(user.mImage, 1) ;
        
        if (iData == nil)
        {
            //使用png格式轉化
            //png無壓縮格式
            iData = UIImagePNGRepresentation(user.mImage) ;
            
            if (iData == nil)
            {
                NSLog(@"圖像有誤!");
                
                return NO ;
            }
        }
        
        //得到數據庫中最後一條行數據的ID
        NSInteger lastCount = [fmdb lastInsertRowId] ;
        
        lastCount++ ;
        
        static int count = 0 ;
        count++ ;
        
        NSString* imagePath = [NSString stringWithFormat:@"%@/%@/image_%d.pic",NSHomeDirectory(),@"tmp",count] ;
        
      //  user.mImage ;
        
      //  NSLog(@"ipath = %@",imagePath) ;
        
        //寫入到文件中
        BOOL isWrite = [iData writeToFile:imagePath atomically:YES] ;
        
        if (isWrite == NO) {
            NSLog(@"寫入圖片失敗!");
        }
        
        //執行插入操做
        isInsert = [fmdb executeUpdate:strInsert,user.mName,
                    user.mUserID,
                    [NSNumber numberWithInt:user.mAge],imagePath] ;
        
        //isInsert = YES ;
    }
    
    return isInsert ;
}


@end

使用:數組

#import "ViewController.h"
#import "FMDBMgr.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    FMDBMgr* mgr = [[FMDBMgr alloc] init] ;
    
    [mgr openFMDB] ;
    
    static int count = 1 ;
    
    UserInfo* uInfo = [[UserInfo alloc] init] ;
    uInfo.mAge = 20+count ;
    uInfo.mName = [NSString stringWithFormat:@"name %d",count] ;
    uInfo.mEMail =@"12345555@qq.com" ;
    uInfo.mUserID = [NSString stringWithFormat:@"%d",count] ;
    
    NSString* iName = [NSString stringWithFormat:@"17_%d.jpg",count%15+1] ;
    
    uInfo.mImage = [UIImage imageNamed:iName] ;
    
    count++ ;
    
    BOOL isOK = [mgr insertUserToDB:uInfo] ;
    NSLog(@"OK = %d",isOK) ;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

參考文章:http://techblog.youdao.com/?p=1023atom

相關文章
相關標籤/搜索