bool Logging::Init() { int rc = sqlite3_open("db.sql", &m_db); if (rc) { trace("Can't open Database (%s)\n", sqlite3_errmsg(m_db)); Close(); return false; } int version = GetDBVersion(m_db); if (version == 0) CreateSchema(m_db); else if (version == 1) UpdateV1toV2(m_db); else if (version != 2) CreateSchema(m_db); return true; }
//打开数据库文件 bool CDatabase::OpenDB(std::string sFileName) { //先关闭连接 CloseDB(); _pDB = new CppSQLite3DB(); try { _pDB->open(sFileName.c_str()); } catch(CppSQLite3Exception e) { return false; } catch(...) { return false; } //检测是否成功打开 if(!IsOpen()) return false; try { //词典是否存在 if(!IsExistTable(DicTableName)) {//不存在词典,则新建词典 static const char sSql[] = "CREATE TABLE %Q (key text primary key,value text,comment text)"; if(SQLERROR == this->ExecSql(sSql,DicTableName)) goto _OnError; } if(!OnCreateTables()) goto _OnError; //取得数据库文件版本 const int OldDBVersion = GetDBVersion(); if(OldDBVersion > DBVersion) { goto _OnError; } if(OldDBVersion < DBVersion) { if(!BackupDB(sFileName)) goto _OnError; if(!OnUpdateTables(OldDBVersion,DBVersion)) goto _OnError; DeleteDict(DBVersionKey); if(!InsertDict(DBVersionKey,DBVersion)) goto _OnError; } else { int nLastBackupTime = 0; if(GetDictValue(LastBackupKey,nLastBackupTime)) { int nOffTime = (int)time(NULL) - nLastBackupTime; if(nOffTime > BackupDBRate) BackupDB(sFileName); } } }catch(CppSQLite3Exception e) { assert(false); goto _OnError; } catch(...) { assert(false); goto _OnError; } return true; _OnError: { this->CloseDB(); return false; } }