iOS 数据库升级

分享一段ios数据库代码。包括创建、升级、增删查改。

里面的那些类不必细究,主要是数据库的代码100%可用。

数据库升级部分,使用switch,没有break,低版本一次向高版本修改。

//  DB.h
//iukey
#import
#import "sqlite3.h"
#import "User.h"
#import "ChatInfo.h"
#import "DescInfo.h"
@interface DBHelper : NSObject{
    sqlite3* db;//数据库句柄
//   @public DBHelper *instance;
}

@property(nonatomic,assign)sqlite3* db;
- (BOOL)insertUserWithTUsersName:(NSString*)name account:(NSString*)account pwd:(NSString*)pwd;
- (NSMutableArray*)quary:(NSString*)str;//查询

- (NSString*)getFilePath;//获取数据库路径
- (BOOL)createDB;//创建数据库
- (BOOL)createTable:(NSString*) creteSql;//创建表
- (User*)getUserWithTUsersByAccount:(NSString* )account;
- (BOOL)updateUserPwdWithTUsers:(NSString*)pwd byAccount:(NSString*)account ;
//+ (DBHelper*) getDBhelperInstance;
- (BOOL)deleteItemWithTable:(NSString*)table_ ByKey:(NSString*)key_ ;
-(BOOL)insertChatRecordWithTChatRecordByChatInfo:(ChatInfo*)ci owner:(NSString *)owner;
- (int)getRecordCountWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner;
- (NSMutableArray*)getChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid fromIndex:(int)fromIndex count:(int)count owner:(NSString *)owner;
- (BOOL)deleteChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner;

-(NSMutableDictionary*)getRecordCountNotREadWithTChatRecord:(NSString*)toJid owner:(NSString *)owner;
-(BOOL)updateRecordCountNotReadWithChatRecord:(NSString *)fromJid;
-(NSMutableArray*)getRecordNotReadWithTChatRecordFromJid:(NSString*)fromJid owner:(NSString *)owner;
//history
-(BOOL)insertHistoryRecordWithTHistoryRecordByDescInfo:(DescInfo*)di account:(NSString*)account routerjid:(NSString *)routerjid;
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByAccount:(NSString* )account routerjid:(NSString *)routerjid;
- (BOOL)deleteHistoryWithTHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid;
- (BOOL)deleteHistoryWithTHistoryRecordById:(int)c_id account:(NSString* )account routerjid:(NSString *)routerjid;
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByUDN:(NSString* )UDN withAccount:(NSString* )account routerjid:(NSString *)routerjid;
-(BOOL)updateHistoryCountNotReadWithHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid;
-(int)getHistoryCountNotReadWithHistoryRecordByAccount:(NSString *)account routerjid:(NSString *)routerjid;

@end

//  DB.m
//iukey
#import "DBHelper.h"
#import "YHConfig.h"
#import "DescInfo.h"
#import "FromJid.h"
// tid ----table index id
@implementation DBHelper

static  NSString *createTB_user=@"create table if not exists t_users (c_account text primary key ,c_name text,c_pwd text)";

static  NSString *createTB_info=@"create table if not exists t_info (c_key text primary key ,c_value text)";

static  NSString *createTB_chat_record=@"create table if not exists t_chat_record (c_id integer primary key autoincrement,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text,c_has_read integer)";

static NSString *createTB_history_record=@"create table if not exists t_history_record (c_id integer primary key autoincrement,c_deviceType text,c_UDN text,c_friendlyName text,c_history_time integer,c_desc text)";

@synthesize db;

- (id)init{
    self = [super init];
    int dbVersion =0;
    //检查是否存在数据库文件
    if (![self isExistDB]) {
        //不存在,则创建
         [self createDB];
    }else {
        //若存在,检测数据库版本,则进行升级,

        char* info=NULL;
        [self getDBInfoValueWithKey:"db_version" value:&info];
        if(info == NULL){
            return self;
        }
        dbVersion= atoi(info);
        free (info);

    }
    //升级数据库。若第一次创建,则从0开始升级。顺序升级,因此不可以有break
    switch (dbVersion) {
        case 0:
            //第一次,新建并初始化各表
            [self createTable:createTB_user];
            //记录版本
            [self createTable:createTB_info];
            [self setDBInfoValueWithKey:"db_version" value:"1"];
            [self createTable:createTB_chat_record];
            [self createTable:createTB_history_record];
        case 1:
            [self setDBInfoValueWithKey:"db_version" value:"2"];
        case 2:
        {
            NSString *modify=@"alter table t_history_record add column c_user text not null default ‘‘";
            [self setDBInfoValueWithKey:"db_version" value:"3"];
            [self execSql:modify];
        }
        case 3:
        {
            NSString *modify=@"alter table t_chat_record add column c_owner text not null default ‘‘";
            [self setDBInfoValueWithKey:"db_version" value:"4"];
            [self execSql:modify];
        }
        case 4:
        {
            NSString *modify=@"alter table t_history_record add column c_router text not null default ‘‘";
            [self setDBInfoValueWithKey:"db_version" value:"5"];
            [self execSql:modify];
        }
        case 5:
        {
            NSString *modify=@"alter table t_history_record add column c_has_read integer not null default ‘‘";
            [self setDBInfoValueWithKey:"db_version" value:"6"];
            [self execSql:modify];
        }
            //注:数据库升级时候,只需要一次添加case即可,同时更新db_version值

        default:
            break;
    }
    return self;
}

- (NSString*)getFilePath{//get db path
    NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask  , YES);
    NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:[YHConfig DBName ]];
    return databaseFilePath ;
}

#pragma mark db manage
- (BOOL)createDB{
    int ret = sqlite3_open([[self getFilePath] UTF8String], &db);//打开数据库,数据库不存在则创建
    if (SQLITE_OK == ret) {//创建成功
        sqlite3_close(db);//关闭
        return YES;
    }else{
        return NO;//创建失败
    }
}
-(BOOL) isExistDB{
    NSFileManager* fm = [[[NSFileManager alloc] init]autorelease];
    return [fm fileExistsAtPath:[self getFilePath] ];
}

- (BOOL)dropTableWithTableName:(NSString*) tableName{
    NSString* dropSql = [[NSString alloc] initWithFormat:@"delete table %@",tableName];
    return [self execSql:[dropSql autorelease]];
}
- (BOOL)createTable:(NSString*) creteSql{
    return [self execSql:creteSql];
   }
-(BOOL) execSql:(NSString*) creteSql{
    char* err;
    const char* sql = [creteSql UTF8String];//创建表语句
    if (sql==NULL) {
        return NO;
    }
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
        return NO;
    }

    if (SQLITE_OK == sqlite3_exec(db, sql, NULL, NULL, &err)) {//执行创建表语句成功
        sqlite3_close(db);
        return YES;
    }else{//创建表失败
        return NO;
    }

}
//"select * from dictionary where en like ? or cn like ? or comment like ?;";//查询语句
//TODO
- (NSMutableArray*)quary:(NSString *) querySql{

    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
        return nil;
    }
    const char* sql = [querySql UTF8String];//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
        //        sqlite3_bind_text(stmt, 1,[[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL);
        //        sqlite3_bind_text(stmt, 2, [[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL);
        //        sqlite3_bind_text(stmt, 3, [[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL);
    }else{
        return nil;
    }
    NSMutableArray* arr =[[NSMutableArray alloc]init];//存放查询结果
    while( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        char* _en = (char*)sqlite3_column_text(stmt, 1);
        char* _cn = (char*)sqlite3_column_text(stmt, 2);
        char* _comment = (char*)sqlite3_column_text(stmt, 3);

        NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];//单条纪录
        [dict setObject:[NSString stringWithCString:_en encoding:NSUTF8StringEncoding] forKey:@"kEN"];
        [dict setObject:[NSString stringWithCString:_cn encoding:NSUTF8StringEncoding] forKey:@"kCN"];
        [dict setObject:[NSString stringWithCString:_comment encoding:NSUTF8StringEncoding] forKey:@"kCOMMENT"];
        [arr addObject:dict];//插入到结果数组
        [dict release];
    }
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return [arr autorelease];//返回查询结果数组
}

#pragma mark  table t_info manage
- (void)getDBInfoValueWithKey:(const char*)key value:(char**)value{
    //TODO
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        printf("%s:%d query error..\n",__FUNCTION__,__LINE__);
        return ;
    }
    const char* sql = "select * from t_info where c_key =?";//查询语句
    sqlite3_stmt* stmt;

    int error = sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    if (error==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1,key, -1, NULL);
    }else{
        printf("%s:%d query error.. %d\n",__FUNCTION__,__LINE__,error);
        return;
    }

    if( SQLITE_ROW == sqlite3_step(stmt) ){//执行
         char* v= (char*)sqlite3_column_text(stmt, 1);
        *value = strdup(v);

    }
    sqlite3_finalize(stmt);
    sqlite3_close(db);
}
- (BOOL)setDBInfoValueWithKey:(const char*)key value:(const char*)value {
    char* info=NULL;
    [self getDBInfoValueWithKey:key value:&info];
    if (info!= NULL) {
        //存在,则更新
        [self updateDBInfoValueWithKey:key value:value];
    }else{
        //不存在,插入
        [self insertDBInfoValueWithKey:key value:value];

    }
    free(info);
    return YES;
}

- (BOOL)insertDBInfoValueWithKey:(const char*)key value:(const char*)value{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
        return NO;
    }
    const char* sql = "insert into t_info(c_key,c_value) values(?,?);";
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, key, -1, NULL);//绑定参数
        sqlite3_bind_text(stmt, 2, value, -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)updateDBInfoValueWithKey:(const char*)key value:(const char*)value{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
        return NO;
    }
    const char* sql = "update t_info set c_value = ? where c_key = ?;";
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, value, -1, NULL);
        sqlite3_bind_text(stmt, 2, key, -1, NULL);
    }else{
        return NO;
    }
    ret = sqlite3_step(stmt);
    printf("ret:%d\n",ret);
    if (SQLITE_DONE ==ret ) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}

#pragma mark table "t_users" manage
- (User*)getUserWithTUsersByAccount:(NSString* )account{

    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }

    const char* sql = "select * from t_users where c_account = ?";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1,[account UTF8String], -1, NULL);
    }else{
        return nil;
    }
    User* user = nil;
    if( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        user = [[[User alloc]init]autorelease];
        NSString *name=nil;
        NSString *pwd= nil;
        if (sqlite3_column_text(stmt, 0) != NULL) {
            name = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];

        }
        if (sqlite3_column_text(stmt,2 ) != NULL) {
            pwd = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 2)];
        }

        user.name =name;
        user.account= account;
        user.pwd = pwd;
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return  user;
}

- (BOOL)insertUserWithTUsersName:(NSString*)name account:(NSString*)account pwd:(NSString*)pwd{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    const char* sql = "insert into t_users(c_name,c_account,c_pwd) values(?,?,?);";
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, [name UTF8String], -1, NULL);//绑定参数
        sqlite3_bind_text(stmt, 2, [account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [pwd UTF8String], -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}

//根据account 修改用户 的name和pwd
- (BOOL)updateUserPwdWithTUsers:(NSString*)pwd byAccount:(NSString*)account {
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    const char* sql = "update t_users set c_pwd = ? where c_account = ?";
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, [pwd UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [account UTF8String], -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}
#pragma mark table "t_chat_record" manage
-(BOOL)insertChatRecordWithTChatRecordByChatInfo:(ChatInfo*)ci owner:(NSString *)owner{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    //@"create table if not exists t_chat_record (c_id text primary key ,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text)";
    const char* sql = "insert into t_chat_record(c_from_jid,c_to_jid,c_chat_time,c_msg,c_has_read,c_owner) values(?,?,?,?,?,?);";
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, [[ci fromJid] UTF8String], -1, NULL);//绑定参数
        sqlite3_bind_text(stmt, 2, [[ci toJid] UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 3, (int)[ci.chatTime timeIntervalSince1970] );
        sqlite3_bind_text(stmt, 4, [ci.msg UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 5, [ci hasRead]);
        sqlite3_bind_text(stmt, 6, [owner UTF8String], -1, NULL);
        log4debug(@"%d",[ci hasRead]);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }

}
//update the count of chat record not read
-(BOOL)updateRecordCountNotReadWithChatRecord:(NSString *)fromJid
{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    const char* sql = "update t_chat_record set c_has_read = 1 where c_from_jid = ?";//修改语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
            sqlite3_bind_text(stmt, 1, [fromJid UTF8String], -1, NULL);

        }else{
            return nil;
        }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }

}

-(NSMutableArray*)getRecordNotReadWithTChatRecordFromJid:(NSString*)fromJid owner:(NSString *)owner{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    const char* sql = "select c_chat_time,c_msg from t_chat_record where c_has_read = 0 and c_from_jid =? and c_owner =? order by c_chat_time asc";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
       sqlite3_bind_text(stmt, 1,[fromJid UTF8String], -1, NULL);
       sqlite3_bind_text(stmt, 2,[owner UTF8String], -1, NULL);
    }else{
        return nil;
    }

    NSMutableArray* msgs=[[[NSMutableArray alloc]init]autorelease];
    while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        NSString *msg=nil;
        int chatTime = 0;
        if (sqlite3_column_text(stmt, 1) != NULL) {
            msg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 1)];

        }
        chatTime = sqlite3_column_int(stmt, 0);
        NSDate * showTime = [NSDate dateWithTimeIntervalSince1970:chatTime];
        [msgs addObject:showTime];
        [msgs addObject:msg];

    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return msgs ;
}

//get the count of the chat record not read
-(NSMutableDictionary*)getRecordCountNotREadWithTChatRecord:(NSString*)toJid owner:(NSString *)owner
{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    const char* sql = "select c_from_jid, count(*) from t_chat_record where c_has_read = 0 and c_to_jid =? and c_owner =? group by c_from_jid ";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
             sqlite3_bind_text(stmt, 1,[toJid UTF8String], -1, NULL);
             sqlite3_bind_text(stmt, 2,[owner UTF8String], -1, NULL);
    }else{
        return nil;
    }

    NSMutableDictionary* fis=[[[NSMutableDictionary alloc]init]autorelease];
    while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
       FromJid* fi  = [[[FromJid alloc]init]autorelease];
        NSString *fromJid=nil;
        int noReadCount = 0;

        if (sqlite3_column_text(stmt, 0) != NULL) {
            fromJid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
        }
        noReadCount = sqlite3_column_int(stmt, 1);

        fi.fromJid = fromJid;
        fi.noReadCount = noReadCount;
        [fis setObject:fi forKey:fi.fromJid];
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return fis ;

}

//get the count of the chat record
- (int)getRecordCountWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner
{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    //static  NSString *[email protected]"create table if not exists t_chat_record (c_id integer primary key autoincrement,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text)";
    //不区分from&to,因此两个条件查询
    const char* sql = "select count (*) from t_chat_record where ((c_from_jid = ? and c_to_jid=?) or  (c_from_jid = ? and c_to_jid=?)) and c_owner = ?";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1,[oneJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2,[anotherJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3,[anotherJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4,[oneJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 5,[owner UTF8String], -1, NULL);
    }else{
        return nil;
    }
    int count=0;
    if ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        count=sqlite3_column_int(stmt, 0);
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return  count ;
}

- (NSMutableArray*)getChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid fromIndex:(int)fromIndex count:(int)count owner:(NSString *)owner
{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    //static  NSString *[email protected]"create table if not exists t_chat_record (c_id integer primary key autoincrement,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text)";
    //不区分from&to,因此两个条件查询
    const char* sql = "select * from t_chat_record where ((c_from_jid = ? and c_to_jid=?) or  (c_from_jid = ? and c_to_jid=?)) and c_owner = ? order by c_chat_time asc limit ?,?  ";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1,[oneJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2,[anotherJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3,[anotherJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4,[oneJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 5,[owner UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 6, fromIndex);
        sqlite3_bind_int(stmt, 7, count);
    }else{
        return nil;
    }
    NSMutableArray *cis=[[[NSMutableArray alloc]initWithCapacity:3]autorelease];
    while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        ChatInfo* ci  = [[[ChatInfo alloc]init]autorelease];
        NSString *fromJid=nil;
        NSString *toJid= nil;
        NSString *msg=nil;
        int time = 0;
        if (sqlite3_column_text(stmt, 1) != NULL) {
            fromJid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 1)];
        }
        if (sqlite3_column_text(stmt,2 ) != NULL) {
            toJid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 2)];
        }
        if (sqlite3_column_text(stmt,3 ) != NULL) {
            time = sqlite3_column_int(stmt, 3);
        }
        if (sqlite3_column_text(stmt,4 ) != NULL) {
            msg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 4)];
        }
        ci.fromJid=fromJid;
        ci.toJid=toJid;
        ci.chatTime=[NSDate dateWithTimeIntervalSince1970:time];
        ci.msg=msg;
        [cis addObject:ci];
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return  cis ;
}

- (BOOL)deleteChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner
{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    NSString* sql = [NSString stringWithFormat:@"delete from t_chat_record where ((c_from_jid = ? and c_to_jid=?) or  (c_from_jid = ? and c_to_jid=?)) and c_owner = ?"];
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1,[oneJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2,[anotherJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3,[anotherJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4,[oneJid UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 5,[owner UTF8String], -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }

}

#pragma mark table "t_history_record" manage
-(BOOL)insertHistoryRecordWithTHistoryRecordByDescInfo:(DescInfo*)di account:(NSString*)account routerjid:(NSString *)routerjid{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    //@"create table if not exists t_history_record (c_id text primary key ,c_deviceType text,c_UDN text,c_friendlyName text,c_history_time integer,c_desc text)";
    const char* sql = "insert into t_history_record(c_deviceType,c_UDN,c_friendlyName,c_history_time,c_desc,c_user,c_router,c_has_read) values(?,?,?,?,?,?,?,?);";
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, [[di deviceType] UTF8String], -1, NULL);//绑定参数
        sqlite3_bind_text(stmt, 2, [[di deviceUDN] UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [[di friendlyName] UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 4, (int)[di.time timeIntervalSince1970] );
        sqlite3_bind_text(stmt, 5, [di.deviceDesc UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 6, [account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 7, [routerjid UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 8, [di hasRead]);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }

}
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByUDN:(NSString* )UDN withAccount:(NSString* )account routerjid:(NSString *)routerjid
{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    const char* sql = "select * from t_history_record where c_UDN = ? and c_user =? and c_router =? order by c_history_time desc";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1,[UDN UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2,[account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3,[routerjid UTF8String], -1, NULL);
    }else{
        return nil;
    }
    NSMutableArray *dis=[[[NSMutableArray alloc]initWithCapacity:5]autorelease];
    while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        DescInfo* di  = [[[DescInfo alloc]init]autorelease];
        NSString* deviceType = nil;
        NSString* friendlyName= nil;
        NSString* deviceUDN= nil;
        NSString* deviceDesc= nil;
        NSDate* time= nil;
        int c_id = 0;
        if (sqlite3_column_text(stmt, 0) != NULL) {
            c_id = sqlite3_column_int(stmt, 0);

        }
        if (sqlite3_column_text(stmt, 1) != NULL) {
            deviceType = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 1)];
        }
        if (sqlite3_column_text(stmt,2 ) != NULL) {
            deviceUDN = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 2)];
        }
        if (sqlite3_column_text(stmt,3 ) != NULL) {
            friendlyName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 3)];
        }
        if (sqlite3_column_text(stmt,4 ) != NULL) {
            int i  = sqlite3_column_int(stmt, 4);
            time = [NSDate dateWithTimeIntervalSince1970:i];
            //            time = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 4)];
        }
        if (sqlite3_column_text(stmt,5 ) != NULL) {
            deviceDesc = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 5)];
        }
        di.deviceType=deviceType;
        di.deviceUDN=deviceUDN;
        di.friendlyName=friendlyName;
        di.time = time;
        di.deviceDesc =deviceDesc;
        di.c_id = c_id;
        [dis addObject:di];
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return  dis ;

}
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByAccount:(NSString* )account routerjid:(NSString *)routerjid
{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    const char* sql = "select * from t_history_record where c_user = ? and c_router = ? order by c_history_time desc";//查询语句
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, nil)==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1,[account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2,[routerjid UTF8String], -1, NULL);
    }else{
        return nil;
    }
    NSMutableArray *dis=[[[NSMutableArray alloc]initWithCapacity:5]autorelease];
    while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
       DescInfo* di  = [[[DescInfo alloc]init]autorelease];
        NSString* deviceType = nil;
         NSString* friendlyName= nil;
          NSString* deviceUDN= nil;
         NSString* deviceDesc= nil;
        NSDate* time= nil;
        int c_id = 0;
        if (sqlite3_column_text(stmt, 0) != NULL) {
            c_id = sqlite3_column_int(stmt, 0);

        }
        if (sqlite3_column_text(stmt, 1) != NULL) {
            deviceType = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 1)];
        }
        if (sqlite3_column_text(stmt,2 ) != NULL) {
           deviceUDN = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 2)];
        }
        if (sqlite3_column_text(stmt,3 ) != NULL) {
            friendlyName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 3)];
        }
        if (sqlite3_column_text(stmt,4 ) != NULL) {
            int i  = sqlite3_column_int(stmt, 4);
            time = [NSDate dateWithTimeIntervalSince1970:i];
//            time = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 4)];
        }
        if (sqlite3_column_text(stmt,5 ) != NULL) {
            deviceDesc = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 5)];
        }
        di.deviceType=deviceType;
        di.deviceUDN=deviceUDN;
        di.friendlyName=friendlyName;
        di.time = time;
        di.deviceDesc =deviceDesc;
        di.c_id = c_id;
        [dis addObject:di];
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return  dis ;

}
- (BOOL)deleteHistoryWithTHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid
{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    NSString* sql = [NSString stringWithFormat:@"delete from t_history_record where c_deviceType = ? and c_user = ? and c_router = ?"];
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, [deviceType UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [routerjid UTF8String], -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}
- (BOOL)deleteHistoryWithTHistoryRecordById:(int)c_id account:(NSString* )account routerjid:(NSString *)routerjid

{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }
    NSString* sql = [NSString stringWithFormat:@"delete from t_history_record where c_id = ? and c_user = ? and c_router = ?"];
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
//        sqlite3_bind_text(stmt, 1, [c_id UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 1, c_id);
        sqlite3_bind_text(stmt, 2, [account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [routerjid UTF8String], -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }

}

//update the count of history record not read
-(BOOL)updateHistoryCountNotReadWithHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid
{
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    NSString * sql = [NSString stringWithFormat:@"update t_history_record set c_has_read = 1 where c_deviceType = ? and c_user = ? and c_router = ?"];//查询语句
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1, [deviceType UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [routerjid UTF8String], -1, NULL);
    }else{
        return nil;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}

-(int)getHistoryCountNotReadWithHistoryRecordByAccount:(NSString *)account routerjid:(NSString *)routerjid
{
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
        return nil;
    }
    NSString * sql = [NSString stringWithFormat:@"select count (*) from t_history_record where c_has_read = 0 and c_user = ? and c_router = ?"];//查询语句
    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备
        sqlite3_bind_text(stmt, 1, [account UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [routerjid UTF8String], -1, NULL);
    }else{
        return nil;
    }
    int count=0;
    if ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
        count=sqlite3_column_int(stmt, 0);
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return  count ;
}

#pragma mark manage normal tables
- (BOOL)deleteItemWithTable:(NSString*)table_ ByKey:(NSString*)key_ {
    int ret = 0;
    if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
        return NO;
    }

    NSString* sql= [NSString stringWithFormat:@"delete from  %@  where  c_account =  ?",table_]; 

    sqlite3_stmt* stmt;//
    int result =sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    printf("%s\n",sqlite3_errmsg(db));
    if (result==SQLITE_OK) {//准备语句
        sqlite3_bind_text(stmt, 1, [key_ UTF8String], -1, NULL);
    }else{
        return NO;
    }
    if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return YES;
    }else{
        return NO;
    }
}
时间: 2024-11-14 13:29:11

iOS 数据库升级的相关文章

iOS 数据库升级 如何进行操作?

在iOS开发中,经常会遇到数据库升级,修改删除表的某些字段,这就需要我们来进行处理了,下面分析两种数据库的升级处理问题! 1.比如:我们常使用fmdb或者其他方式创建sqlite数据库,但是由于版本迭代问题,常常有需求要更新数据库,比如加字段.删除.修改字段等等,怎么样才能升级数据库且保持原来存的数据有效呢,上代码: const static NSInteger FAMILY_LIST_DB_MANAGER_VER = 1; @implementation KSFamilyListDBManag

iOS coredata 数据库升级 时报Can't find model for source store

在coredata 数据库结构被更改后,没根据要求立即建立新version,而是在原version上进行了小修改,之后才想起来建立新版本.并通过以下代码合并数据库, NSError *error = nil; NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,

探索Oracle之数据库升级二 11.2.0.3升级到11.2.0.4完整步骤

探索Oracle之数据库升级二  11.2.0.3升级到11.2.0.4完整步骤 说明:         这篇文章主要是记录下单实例环境下Oracle 11.2.0.1升级到11.2.0.3的过程,当然RAC的升级是会有所不同.但是他们每个版本之间升级步骤都是差不多的,先升级Database Software,再升级Oracle Instance. Oracle 11.2.0.4的Patchset No:19852360下载需要有Oracle Support才可以.  Patchset包含有7个

数据库升级问题—ORA-39700: database must be opened with UPGRADE option

1. 错误描述 一个数据较长时间未使用了,最近启动时出现如下错误: SQL> startup Oracle instance started. Total System Global Area 4932501504 bytes Fixed Size                  2103096 bytes Variable Size            889194696 bytes Database Buffers        4026531840 bytes Redo Buffers

数据库升级ora-04063 DBMS_REGISTRY has error

在做Oracle数据库从11.2.0.1.0升级到11.2.0.2.8时,软件升级没有问题,实例升级没有问题,升级psu的时候. 运行@?/rdbms/admin/catbundle psu apply时,只显示一部分信息,即终止apply. 在dba_registry_history中未显示11.2.0.2.8的psu信息: select * from dba_registry_history; ACTION_TIME                    ACTION          NA

Android数据库升级、降级、创建(onCreate() onUpgrade() onDowngrade())

数据库版本升级对软件的管理操作. 我们手机经常会收到xxx软件升级什么的提醒,你的软件版本更新,同时你的数据库对应的版本也要相应的更新. 数据库版本更新需要主要的问题: 软件的1.0版本升级到1.1版本时,老的数据不能丢. 那么在1.1版本的程序中就要有地方能够检测出来新的软件版本与老的数据库不兼容,并且能够有办法把1.0软件的数据库升级到1.1软件能够使用的数据库. 换句话说,要在1.0软件的数据库的那个表中增加那个字段,并赋予这个字段默认值. 当然有的时候我们对更新后的 版本并没有什么好感,

[iOS]数据库第三方框架FMDB详细讲解

[iOS]数据库第三方框架FMDB详细讲解 初识FMDB iOS中原生的SQLite API在进行数据存储的时候,需要使用C语言中的函数,操作比较麻烦.于是,就出现了一系列将SQLite API进行封装的库,例如FMDB.PlausibleDatabase.sqlitepersistentobjects等. FMDB是一款简洁.易用的封装库.因此,在这里推荐使用第三方框架FMDB,它是对libsqlite3框架的封装,用起来的步骤与SQLite使用类似,并且它对于多线程的并发操作进行了处理,所以

数据库升级代码学习

  业务场景及需求:全国每一个银行营业网点[指跟公司合作的]产品上线后.肯定须要升级业务以应对新的功能需求,那么数据库每次升级更新时都是在数据库管理工具中运行升级脚本.很不方便.此时需求:可以在业务系统代码中设置开关,须要升级的时候打开开关系统自己主动直接完毕升级. 思路:1)数据库里面有个对应的版本号号,服务里面有个版本号文件[以要升级到的版本号号命名]. 2)升级的时候查出服务里面的版本号和数据库里面的版本号,比对:假设版本号一样不升级.假设版本号不一样就运行服务里面的升级脚本. 以下看看基

Android中数据库升级onUpgrade方法说明

Andoird的SQLiteOpenHelper类中有一个onUpgrade方法.帮助文档中只是说当数据库升级时该方法被触发.经过实践,解决了我一连串的疑问: 1. 帮助文档里说的“数据库升级”是指什么? 你开发了一个程序,当前是1.0版本.该程序用到了数据库.到1.1版本时,你在数据库的某个表中增加了一个字段.那么软件1.0版本用的数据库在软件1.1版本就要被升级了. 2. 数据库升级应该注意什么? 软件的1.0版本升级到1.1版本时,老的数据不能丢.那么在1.1版本的程序中就要有地方能够检测