void DClusterNotifyDataSource::parseDataField(CppSQLite3Query &src, DClusterNotifyDataField &dest) { dest.accountID = atoll(src.fieldValue(0)); dest.notifyType = atoll(src.fieldValue(1)); dest.userID = atoll(src.fieldValue(2)); dest.userName = src.fieldValue(3); dest.clusterID = atoll(src.fieldValue(4)); dest.clusterName = src.fieldValue(5); dest.notifyContent = src.fieldValue(6); dest.notifyVerify = src.fieldValue(7); dest.notifyTime = src.fieldValue(8); dest.status = atoi(src.fieldValue(9)); }
EXPORT_C gint32 CContactDb::GetEntityById(guint32 nId, CDbEntity** ppEntity) { char sql[128] = {0}; *ppEntity = NULL; OpenDatabase(); sprintf(sql, "select * from contact where cid = %d;", nId); CppSQLite3Query query = m_dbBeluga.execQuery(sql); if (query.eof()) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_Not_Exist); } if (ContactType_Phone == query.getIntField(ContactField_Type)) *ppEntity = new CPhoneContact(this, FALSE); else *ppEntity = new CIMContact(this); if (NULL == *ppEntity) { CloseDatabase(); return ERROR(ESide_Client, EModule_Db, ECode_No_Memory); } for (int i=0; i<query.numFields(); i++) { GString * fieldValue = g_string_new(query.fieldValue(i)); (*ppEntity)->SetFieldValue(i, fieldValue); g_string_free(fieldValue, TRUE); } CloseDatabase(); return 0; }
//必须在加载任务列表之后 int CPersistencManager::LoadReadyTaskQueue(CT_DEQUE &ready_list,const CT_MAP& task_map){ if(m_useLevelDB) { string value; leveldb::ReadOptions ro; leveldb::Status s; int ready_count = 0; s = m_LevelDB->Get(ro, TASK_RUN_COUNT, &value); if(s.ok()) ready_count = *(int*)value.data(); CLog::Log(LOG_LEVEL_DEBUG, "LoadReadyTaskQueue: count=%d\n", ready_count); for(int i = 0; i < ready_count; i++) { s = m_LevelDB->Get(ro, TASK_IDX(TASK_RUN_KEY, i), &value); if(s.ok()) { if(task_map.find((char*)value.c_str()) == task_map.end()){ CLog::Log(LOG_LEVEL_WARNING, "Task List and Ready Task List is not Matched\n"); continue; } ready_list.push_back(value); CLog::Log(LOG_LEVEL_DEBUG, "Ready task %d:%s\n", i, value.c_str()); } } return 0; } int ret = 0; CT_MAP::const_iterator cur_iter ; CT_MAP::const_iterator end_iter = task_map.end(); CppSQLite3Query query = m_SQLite3DB.execQuery("select * from ReadyTask"); while (!query.eof()) { cur_iter = task_map.find((char *)query.fieldValue("taskid")); if (cur_iter == end_iter){ CLog::Log(LOG_LEVEL_ERROR,"Task List and Ready Task List is not Matched\n"); query.nextRow(); continue; } ready_list.push_back(cur_iter->first); query.nextRow(); } return ret; }
char* CreateInfoByid(int id) { static char buffer[1024]={0}; static char querybuf[1024]={0}; char* str = "%s 体力%s 武力%s 智力%s 魅力%s 年龄%s 类型 %s"; memset(querybuf,0,1024); try { db.open("database/infodata.db"); sprintf(querybuf,"select heroinfo.name,ti,wu,zhi,mei,age,herotype.name from " " heroinfo,herotype where heroinfo.id=%d and heroinfo.type=herotype.id;",id); CppSQLite3Query q = db.execQuery(querybuf); //nge_charsets_utf8_to_gbk((uint8*)str, (uint8*)querybuf, strlen(str), 1024); if (!q.eof()) { sprintf(buffer,str, q.fieldValue(0),q.fieldValue(1),q.fieldValue(2),q.fieldValue(3), q.fieldValue(4),q.fieldValue(5),q.fieldValue(6)); } db.close(); }catch (CppSQLite3Exception& e){ printf("%s\n",e.errorMessage()); } return buffer; }
int CppSQLite3DB::execScalar(LPCTSTR szSQL) { CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1) throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"), DONT_DELETE_MSG); return _tstoi(q.fieldValue(0)); }
BOOL CDlgMemoAdd::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 //SetBackgroundColor(DialogSubBackgroundColor,TRUE); m_DateTime_ctlTime.SetFormat(_T("yyyy-MM-dd HH:mm")); SetBackgroundColor(DialogSubBackgroundColor,TRUE); m_Button_ctlSave.LoadStdImage(IDB_PNG_SAVE, _T("PNG")); m_Button_ctlCancel.LoadStdImage(IDB_PNG_CANCEL, _T("PNG")); m_Static_ctl1.SetBackgroundColor(DialogSubBackgroundColor,TRUE); //m_Static_ctl1.SetTextColor(StaticCaptionColor,TRUE); m_Static_ctl2.SetBackgroundColor(DialogSubBackgroundColor,TRUE); //m_Static_ctl2.SetTextColor(StaticCaptionColor,TRUE); m_Static_ctl3.SetBackgroundColor(DialogSubBackgroundColor,TRUE); //m_Static_ctl3.SetTextColor(StaticCaptionColor,TRUE); m_Static_ctl4.SetBackgroundColor(DialogSubBackgroundColor,TRUE); //m_Static_ctl4.SetTextColor(StaticCaptionColor,TRUE);*/ /*m_Static_ctl5.SetBackgroundColor(DialogSubBackgroundColor,TRUE); m_Static_ctl5.SetTextColor(StaticCaptionColor,TRUE);*/ try{ CppSQLite3DB db; db.open(CBoBoDingApp::g_strDatabasePath); CString strSQL=_T("select distinct * from CategoryMemo order by ID asc;"); CppSQLite3Query q = db.execQuery(strSQL); CString strCategoryName; while(!q.eof()) { strCategoryName=(q.fieldValue(_T("CategoryName"))); if (strCategoryName.Compare(_T("+"))!=0) { m_Combo_ctlCategory.AddString(strCategoryName); } q.nextRow(); } } catch (CppSQLite3Exception& e) { //AfxMessageBox(e.errorMessage()); } m_Combo_ctlCategory.SetCurSel(0); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE }
// 获取父结点为nParentId的所有结点的数目 int FireFox3PlugIn::GetFavoriteCount(int nParentId) { int nCount = 0; wstring strSql = L"select count(*) as total from moz_bookmarks where parent = " ; strSql += StringHelper::ANSIToUnicode(StringHelper::ConvertFromInt(nParentId)); if( nParentId == BOOKMARKS_MENU) { strSql += BOOKMARKS_MENU_EXCLUED_SQL; } else if ( nParentId == BOOKMARKS_TOOLSBAR) { strSql += BOOKMARKS_TOOLSBAR_EXCLUED_SQL; } CppSQLite3Query Query = m_pSqliteDatabase->execQuery(StringHelper::UnicodeToUtf8(strSql).c_str()); const char* pTotal = Query.fieldValue("total"); nCount = StringHelper::ConvertToInt(Query.fieldValue("total")); strSql = L"select * from moz_bookmarks where parent = " ; strSql += StringHelper::ANSIToUnicode(StringHelper::ConvertFromInt(nParentId)); if( nParentId == BOOKMARKS_MENU) { strSql += BOOKMARKS_MENU_EXCLUED_SQL; } else if ( nParentId == BOOKMARKS_TOOLSBAR) { strSql += BOOKMARKS_TOOLSBAR_EXCLUED_SQL; } Query = m_pSqliteDatabase->execQuery(StringHelper::UnicodeToUtf8(strSql).c_str()); while(!Query.eof()) { int nId = Query.getIntField("id", 0); nCount += GetFavoriteCount(nId); Query.nextRow(); } return nCount; }
void COrderManagerDlg::UpdateMenuList() { CListCtrl* MenuList = (CListCtrl*)this->GetDlgItem(IDC_LIST_ORDERMGR_MENUS); char szQuery[1024] = { 0 }; int index = 0; MenuList->DeleteAllItems(); sprintf_s(szQuery, "select menu_name,menu_price from tblMenu order by menu_name"); CppSQLite3Query data = g_SqlMgr.execQuery(szQuery); while (!data.eof()) { index = MenuList->GetItemCount(); MenuList->InsertItem(index, data.fieldValue(0)); MenuList->SetItemText(index, 1, data.fieldValue(1)); data.nextRow(); } UpdateData(FALSE); }
int CppSQLite3DB::execScalar(const CString& strSQL) { CppSQLite3Query q = execQuery(strSQL); if (q.eof() || q.numFields() < 1) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Invalid scalar query"); } return atoi(q.fieldValue(0)); }
int CppSQLite3DB::execScalar(const char* szSQL) { CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1) { IwError(("Invalid scalar query")); } return atoi(q.fieldValue(0)); }
void CLocationDialog::ReadDB() { m_ctlLocationList.DeleteAllItems(); // // Read data // CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB; CppSQLite3Query q = pDB->execQuery("select id,name from Locations;"); // while (!q.eof()) { TRACE("%s %s\n",q.fieldValue(0),q.fieldValue(1)); int nIndex = m_ctlLocationList.InsertItem(1,q.fieldValue(1)); m_ctlLocationList.SetItemData(nIndex,atoi(q.fieldValue(0))); q.nextRow(); } q.finalize(); m_ctlEditButton.EnableWindow(FALSE); m_ctlDeleteButton.EnableWindow(FALSE); }
int CppSQLite3DB::execScalar(const TCHAR* szSQL) { CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1) { throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"), DONT_DELETE_MSG); } return ATOI(q.fieldValue(0)); }
int CppSQLite3DB::execScalar(const char* szSQL) { CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1) { // throw CppSQLite3Exception(CPPSQLITE_ERROR, // "Invalid scalar query", // DONT_DELETE_MSG); } return atoi(q.fieldValue(0)); }
void CDlgEventList::ShowPage(int nPageIndex) { CString str; int i = 0; int nStartIndex = 0; int nOffset = 0; CppSQLite3DB db; db.open(PATH_SQLITE_DB_808); //打开数据库 //查询记录总数量 m_nRecordCount = db.execScalar("SELECT count(*) FROM event_info;"); //计算总页数 if(m_nRecordCount > 0) m_nPageCount = (m_nRecordCount-1)/elist_count+1; else m_nPageCount = 1; //在数据库中查询第nPageIndex页的elist_count条数据 char szSqlBuffer[512]; sprintf(szSqlBuffer, "SELECT * FROM event_info ORDER BY event_ID DESC LIMIT %d, %d;", nPageIndex*elist_count, elist_count); CppSQLite3Query q = db.execQuery(szSqlBuffer); for( i = 0; i < elist_count; i++ ) { if ( !q.eof() ) //数据行 { m_nEvent_ID[i] = q.getIntField("event_ID"); m_list[i].chChar = q.fieldValue("event_content"); m_list[i].nState = BTN_STATE_NORMAL; q.nextRow(); } else //空白行 { m_ItemState[i] = 0; m_list[i].chChar = _T(""); m_list[i].nState = BTN_STATE_DISABLE; } } //释放statement q.finalize(); db.close(); //关闭数据库 return; }
int CPersistencManager::LoadClientInfo(CI_VECTOR &client_list){ if(m_useLevelDB) { return 0; } int ret = 0; int type = 0; CppSQLite3Query query = m_SQLite3DB.execQuery("select * from Client"); while (!query.eof()) { CClientInfo *pCI = new CClientInfo(); if (!pCI){ CLog::Log(LOG_LEVEL_ERROR,"Alloc object CClientInfo Error\n"); return -1; } type = query.getIntField("type"); if (type == COMPUTE_TYPE_CLIENT){ ((CCompClient*)pCI)->m_gputhreads = query.getIntField("gpu"); ((CCompClient*)pCI)->m_cputhreads = query.getIntField("cpu"); } pCI->m_type = type; memset(pCI->m_ip,0,sizeof(pCI->m_ip)); memset(pCI->m_guid,0,sizeof(pCI->m_guid)); memset(pCI->m_hostname,0,sizeof(pCI->m_hostname)); memset(pCI->m_osinfo,0,sizeof(pCI->m_osinfo)); memcpy(pCI->m_ip,query.fieldValue("ip"),strlen(query.fieldValue("ip"))); memcpy(pCI->m_hostname,query.fieldValue("hostname"),strlen(query.fieldValue("hostname"))); memcpy(pCI->m_osinfo,query.fieldValue("osinfo"),strlen(query.fieldValue("osinfo"))); //keeplive time and logintime client_list.push_back(pCI); query.nextRow(); } return ret; }
/** * Metodo para executar a contagem de registros */ long CTableBase::Count(CppSQLite3DB *pDB) { long count = 0; CString s = BuildCountQuery(); CStr s1(s); CppSQLite3Query q = pDB->execQuery(s1); if(!q.eof()) { TCHAR *endp; CString s2(q.fieldValue(0)); count = _tcstol(s2, &endp, 10); } q.finalize(); return count; }
int GetInfoCount() { int count = 0; try { db.open("database/infodata.db"); CppSQLite3Query q = db.execQuery("select count(*) from heroinfo;"); if (!q.eof()) { count = atoi(q.fieldValue(0)); } db.close(); }catch (CppSQLite3Exception& e){ printf("%s\n",e.errorMessage()); } return count; }
BOOL CDlgWebsiteAdd::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 //SetBackgroundColor(DialogBackgroundColor,TRUE); SetBackgroundColor(DialogSubBackgroundColor,TRUE); m_Button_ctlSave.LoadStdImage(IDB_PNG_SAVE, _T("PNG")); m_Button_ctlCancel.LoadStdImage(IDB_PNG_CANCEL, _T("PNG")); //m_Button_ctlSave.SetSkin(IDB_BITMAP_BUTTON_MID_NORMAL,IDB_BITMAP_BUTTON_MID_PRESSED,IDB_BITMAP_BUTTON_MID_ON,0,0,0,0,1,0); //m_Button_ctlCancel.SetSkin(IDB_BITMAP_BUTTON_MID_NORMAL,IDB_BITMAP_BUTTON_MID_PRESSED,IDB_BITMAP_BUTTON_MID_ON,0,0,0,0,1,0); try{ CppSQLite3DB db; db.open(CBoBoDingApp::g_strDatabasePath); CString strSQL=_T("select distinct * from CategoryWebsite order by ID asc;"); CppSQLite3Query q = db.execQuery(strSQL); CString strCategoryName; while(!q.eof()) { strCategoryName=(q.fieldValue(_T("CategoryName"))); if (strCategoryName.Compare(_T("+"))!=0) { m_Combo_ctlCategory.AddString(strCategoryName); } q.nextRow(); } } catch (CppSQLite3Exception& e) { //AfxMessageBox(e.errorMessage()); } m_Combo_ctlCategory.SetCurSel(0); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE }
Char::Char(Uint64 serial, Uint16 type, Uint32 dbId, Client& client) :IMoveableObject(serial, type), myId(dbId), myClient(client) { if (dbId != 0) {// The account has a valid character attached. try{ CppSQLite3DB accDb; accDb.open(DB_ACCOUNTS); std::string query = "SELECT * FROM characters WHERE id = \""+boost::lexical_cast< std::string >(myId)+"\";"; CppSQLite3Query q = accDb.execQuery(query.c_str()); if (!q.eof()){ setName(q.fieldValue(2)); setPosition(Location(q.getIntField(3),q.getIntField(4),q.getIntField(5))); mDestPos = mPos; // We set our destination to our actual location. // Since everything went fine we add the client to the list of active clients. (client.getServer()).addClient(&client); } else{ Logger::getInstance()->log("Error creating Character with ID "+boost::lexical_cast< std::string >(myId) +" no such character in DB!", LOGMODE_DB); } accDb.close(); } catch(CppSQLite3Exception e){ std::string error = "Error creating Character with ID "+boost::lexical_cast< std::string >(myId)+ ", SQLite says: "+ e.errorMessage(); Logger::getInstance()->log(error, LOGMODE_DB); (myClient.getServer()).getConsole().printMsg(error, CONSOLE_ERROR); } } else{ // Create a dummy char setName("Dummy"); setPosition(Location(0,0,0)); mDestPos = mPos; (client.getServer()).addClient(&client); } }
void CDlgAnswerList::ShowPage(int nPageIndex) { CString str = _T(""); int i = 0; int nStartIndex = 0; int nOffset = 0; CppSQLite3Table t; CppSQLite3Query q; CppSQLite3DB db; db.open(PATH_SQLITE_DB_808); //打开数据库 char szSqlBuffer[1024]; memset(szSqlBuffer, 0, sizeof(szSqlBuffer)); //查询记录总数量 // sprintf(szSqlBuffer, "SELECT COUNT(*) FROM answer \ // WHERE UID IN (SELECT UID FROM question ORDER BY question_datatime DESC LIMIT %d, 1) \ // ORDER BY answer_ID;", // m_nQuestionIndex); // m_nRecordCount = db.execScalar( szSqlBuffer ); sprintf(szSqlBuffer, "SELECT * FROM answer where UID = '%d';", m_nQuestionIndex); t = db.getTable(szSqlBuffer); m_nRecordCount = t.numRows(); //计算总页数 if(m_nRecordCount > 0) m_nPageCount = (m_nRecordCount-1)/elist_count+1; else m_nPageCount = 1; memset(szSqlBuffer, 0, sizeof(szSqlBuffer)); sprintf(szSqlBuffer, "SELECT * FROM question where UID = '%d';", m_nQuestionIndex); q = db.execQuery(szSqlBuffer); int nFlag = q.getIntField("flag"); const char* ccText = q.fieldValue("question_content"); str = ccText; //在数据库中查询第nPageIndex页的elist_count条数据 // sprintf(szSqlBuffer, "SELECT * FROM answer \ // WHERE UID IN (SELECT UID FROM question ORDER BY question_datatime DESC LIMIT %d, 1) \ // ORDER BY answer_ID LIMIT %d, %d;", // m_nQuestionIndex, nPageIndex*elist_count, elist_count); // q = db.execQuery(szSqlBuffer); memset(szSqlBuffer, 0, sizeof(szSqlBuffer)); sprintf(szSqlBuffer, "SELECT * FROM answer where UID = '%d' LIMIT %d, %d;", m_nQuestionIndex, (nPageIndex)*elist_count, elist_count); q = db.execQuery(szSqlBuffer); for( i = 0; i < elist_count; i++ ) { if ( !q.eof() ) //数据行 { m_nAnswerID[i] = q.getIntField("answer_ID"); m_list[i].chChar = q.fieldValue("answer_content"); m_list[i].nState = BTN_STATE_NORMAL; q.nextRow(); } else //空白行 { m_ItemState[i] = 0; m_list[i].chChar = _T(""); m_list[i].nState = BTN_STATE_DISABLE; } } //释放statement q.finalize(); db.close(); //关闭数据库 if(nFlag) TTSSpeaking( str ); return; }
int Chat::GroupMessage(int32_t AuthCode, int64_t fromGroup, int64_t fromQQ, const char *msg) { string sql_create = "create table if not exists t_b_preset_message (id INTEGER PRIMARY KEY ASC AUTOINCREMENT, key_word TEXT, value_word TEXT, isdel INT DEFAULT (0));"; char * errmsg = NULL; sqlite3_exec(mpDB, sql_create.c_str(), 0, 0, &errmsg ); if(fromGroup == 194106997) { char szOutput[2] = {0}; strncpy(szOutput, msg, 1); if(strcmp("#", szOutput) == 0) { //CQ_sendGroupMsg(AuthCode, fromGroup, "OK"); char *instructionSet[4096]; int nSetSize = 0; MySplit((char*)msg, "#",instructionSet, &nSetSize); char *order = instructionSet[0]; if(strcmp("关闭", order) == 0) { CQ_sendGroupMsg(AuthCode, fromGroup, "再见, 再也不见!"); isSendMsg = 0; return EVENT_BLOCK; } else if(strcmp("开启", order) == 0) { CQ_sendGroupMsg(AuthCode, fromGroup, "AV8D, 我回来啦!!!"); isSendMsg = 1; return EVENT_BLOCK; } else if(strcmp("教学", order) == 0) { string question = instructionSet[1]; string answer = instructionSet[2]; char szInsertSQL[1000] = {0}; sprintf(szInsertSQL, "INSERT INTO t_b_preset_message (key_word, value_word) VALUES('%s', '%s');", question.c_str(), answer.c_str()); db.execDML(szInsertSQL); CQ_sendGroupMsg(AuthCode, fromGroup, "又学了一句!"); return EVENT_BLOCK; } } } if (isSendMsg == 1) { char szSelectSQL[200] = {0}; sprintf(szSelectSQL, "select value_word from t_b_preset_message where key_word='%s' and isdel=0", msg); query = db.execQuery(szSelectSQL); int sendNum = MyRand(query.numFields()); int index = 0; while (!query.eof()) { if (index++ == sendNum) { CQ_sendGroupMsg(AuthCode, fromGroup, query.fieldValue(0)); return EVENT_BLOCK; } query.nextRow(); } CQ_getLoginNick(AuthCode); const char * szInfo = CQ_getGroupMemberInfoV2(AuthCode, fromGroup, fromQQ, FALSE); return EVENT_IGNORE; } return EVENT_IGNORE; }
void testCppSQLite() { try { int i, fld; time_t tmStart, tmEnd; remove(gszFile); CppSQLite3DB* db = getSQLiteDB(); cout << "SQLite Version: " << db->SQLiteVersion() << endl; cout << endl << "Creating emp table" << endl; db->execDML("create table emp(empno int, empname char(20));"); /////////////////////////////////////////////////////////////// // Execute some DML, and print number of rows affected by each one /////////////////////////////////////////////////////////////// cout << endl << "DML tests" << endl; int nRows = db->execDML("insert into emp values (7, 'David Beckham');"); cout << nRows << " rows inserted" << endl; nRows = db->execDML( "update emp set empname = 'Christiano Ronaldo' where empno = 7;"); cout << nRows << " rows updated" << endl; nRows = db->execDML("delete from emp where empno = 7;"); cout << nRows << " rows deleted" << endl; ///////////////////////////////////////////////////////////////// // Transaction Demo // The transaction could just as easily have been rolled back ///////////////////////////////////////////////////////////////// int nRowsToCreate(50000); cout << endl << "Transaction test, creating " << nRowsToCreate; cout << " rows please wait..." << endl; tmStart = time(0); db->execDML("begin transaction;"); for (i = 0; i < nRowsToCreate; i++) { char buf[128]; sprintf(buf, "insert into emp values (%d, 'Empname%06d');", i, i); db->execDML(buf); } db->execDML("commit transaction;"); tmEnd = time(0); //////////////////////////////////////////////////////////////// // Demonstrate CppSQLiteDB::execScalar() //////////////////////////////////////////////////////////////// cout << db->execScalar("select count(*) from emp;") << " rows in emp table in "; cout << tmEnd-tmStart << " seconds (that was fast!)" << endl; //////////////////////////////////////////////////////////////// // Re-create emp table with auto-increment field //////////////////////////////////////////////////////////////// cout << endl << "Auto increment test" << endl; db->execDML("drop table emp;"); db->execDML( "create table emp(empno integer primary key, empname char(20));"); cout << nRows << " rows deleted" << endl; for (i = 0; i < 5; i++) { char buf[128]; sprintf(buf, "insert into emp (empname) values ('Empname%06d');", i+1); db->execDML(buf); cout << " primary key: " << db->lastRowId() << endl; } /////////////////////////////////////////////////////////////////// // Query data and also show results of inserts into auto-increment field ////////////////////////////////////////////////////////////////// cout << endl << "Select statement test" << endl; CppSQLite3Query q = db->execQuery("select * from emp order by 1;"); for (fld = 0; fld < q.numFields(); fld++) { cout << q.fieldName(fld) << "(" << q.fieldDeclType(fld) << ")|"; } cout << endl; while (!q.eof()) { cout << q.fieldValue(0) << "|"; cout << q.fieldValue(1) << "|" << endl; q.nextRow(); } /////////////////////////////////////////////////////////////// // SQLite's printf() functionality. Handles embedded quotes and NULLs //////////////////////////////////////////////////////////////// cout << endl << "SQLite sprintf test" << endl; CppSQLite3Buffer bufSQL; bufSQL.format("insert into emp (empname) values (%Q);", "He's bad"); cout << (const char*)bufSQL << endl; db->execDML(bufSQL); bufSQL.format("insert into emp (empname) values (%Q);", NULL); cout << (const char*)bufSQL << endl; db->execDML(bufSQL); //////////////////////////////////////////////////////////////////// // Fetch table at once, and also show how to // use CppSQLiteTable::setRow() method ////////////////////////////////////////////////////////////////// cout << endl << "getTable() test" << endl; CppSQLite3Table t = db->getTable("select * from emp order by 1;"); for (fld = 0; fld < t.numFields(); fld++) { cout << t.fieldName(fld) << "|"; } cout << endl; for (int row = 0; row < t.numRows(); row++) { t.setRow(row); for (int fld = 0; fld < t.numFields(); fld++) { if (!t.fieldIsNull(fld)) cout << t.fieldValue(fld) << "|"; else cout << "NULL" << "|"; } cout << endl; } //////////////////////////////////////////////////////////////////// // Test CppSQLiteBinary by storing/retrieving some binary data, checking // it afterwards to make sure it is the same ////////////////////////////////////////////////////////////////// cout << endl << "Binary data test" << endl; db->execDML("create table bindata(desc char(10), data blob);"); unsigned char bin[256]; CppSQLite3Binary blob; for (i = 0; i < sizeof bin; i++) { bin[i] = i; } blob.setBinary(bin, sizeof bin); bufSQL.format("insert into bindata values ('testing', %Q);", blob.getEncoded()); db->execDML(bufSQL); cout << "Stored binary Length: " << sizeof bin << endl; q = db->execQuery("select data from bindata where desc = 'testing';"); if (!q.eof()) { blob.setEncoded((unsigned char*)q.fieldValue("data")); cout << "Retrieved binary Length: " << blob.getBinaryLength() << endl; } const unsigned char* pbin = blob.getBinary(); for (i = 0; i < sizeof bin; i++) { if (pbin[i] != i) { cout << "Problem: i: ," << i << " bin[i]: " << pbin[i] << endl; } } ///////////////////////////////////////////////////////// // Pre-compiled Statements Demo ///////////////////////////////////////////////////////////// cout << endl << "Transaction test, creating " << nRowsToCreate; cout << " rows please wait..." << endl; db->execDML("drop table emp;"); db->execDML("create table emp(empno int, empname char(20));"); tmStart = time(0); db->execDML("begin transaction;"); CppSQLite3Statement stmt = db->compileStatement( "insert into emp values (?, ?);"); for (i = 0; i < nRowsToCreate; i++) { char buf[16]; sprintf(buf, "EmpName%06d", i); stmt.bind(1, i); stmt.bind(2, buf); stmt.execDML(); stmt.reset(); } db->execDML("commit transaction;"); tmEnd = time(0); cout << db->execScalar("select count(*) from emp;") << " rows in emp table in "; cout << tmEnd-tmStart << " seconds (that was even faster!)" << endl; cout << endl << "End of tests" << endl; } catch (CppSQLite3Exception& e) { cerr << e.errorCode() << ":" << e.errorMessage() << endl; } }
int CDbMeter::GroupCommand(const char* dbfilename, int nGroupKey, vector<char*> vbufMember, MIBValue* pValue, int cnt) { try { CppSQLite3DB db; db.open(dbfilename); CppSQLite3Buffer bufSQL; CppSQLite3Query q; CppSQLite3Table t; FILE *fp; char szCmd[12] = {0, }; char szFileName[20] = {0, }; bufSQL.format("SELECT groups.GroupKey, groups.GroupName, groupmember.EUI64ID FROM groups LEFT OUTER JOIN groupmember ON groups.GroupKey=groupmember.GroupKey WHERE groupmember.GroupKey=%d;", nGroupKey); t = db.getTable(bufSQL); for ( int row = 0; row < t.numRows(); row++) { t.setRow(row); if( !t.fieldIsNull(1)) { VARAPI_OidToString(&pValue[1].stream.id, szCmd); bufMember.push_back((char*)t.fieldValue(2)); XDEBUG("%d | %s | %s\r\n", atoi(t.fieldValue(0)), t.fieldValue(1), t.fieldValue(2) ); bufSQL.clear(); bufSQL.format("SELECT datetime('now', 'localtime');"); q = db.execQuery(bufSQL); sprintf(szFileName,"/app/sqlite/%s.txt", t.fieldValue(2)); fp = fopen(szFileName,"a+t"); for (int paramcnt=2; paramcnt<cnt; paramcnt++) { if( VARAPI_OidCompare( &(pValue[paramcnt].oid), "1.11") == 0 ) { fprintf(fp, "%s", pValue[paramcnt].stream.p); } else if( VARAPI_OidCompare( &(pValue[paramcnt].oid), "1.5") == 0 || VARAPI_OidCompare( &(pValue[paramcnt].oid), "1.8") == 0 ) { fprintf(fp, "%d", pValue[paramcnt].stream.u16); } else if( VARAPI_OidCompare( &(pValue[paramcnt].oid), "1.6") == 0 || VARAPI_OidCompare( &(pValue[paramcnt].oid), "1.9") == 0) { fprintf(fp, "%d", pValue[paramcnt].stream.u32); } else { fprintf(fp, "%d", pValue[paramcnt].stream.u8); } if(paramcnt < cnt - 1) fprintf(fp, "|"); } fprintf(fp,"\n"); fclose(fp); XDEBUG("Success: File write!!\r\n"); bufSQL.clear(); XDEBUG("CMD: %s\r\n", szCmd); bufSQL.format("INSERT INTO command(GroupKey, EUI64ID, GroupName, CommandState, Command, CommandCreateTime, ResultErrorCode, ParamPathInfo) VALUES(%d, %Q, %Q, %d, %s, %Q, %d, %Q);", nGroupKey, t.fieldValue(2), t.fieldValue(1), 1, szCmd, q.fieldValue(0), 0, "CmdParamPathInfo.txt" ); db.execDML(bufSQL); } } db.close(); } catch( CppSQLite3Exception& e ) { XDEBUG("%s\r\n",e.errorMessage()); return e.errorCode(); } return SQLITE_OK; }
BOOL CDlgZiJinLiuShuiShouRuChange::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 //SetBackgroundColor(DialogBackgroundColor,TRUE); SetBackgroundColor(DialogSubBackgroundColor,TRUE); m_Button_ctlSave.LoadStdImage(IDB_PNG_SAVE, _T("PNG")); m_Button_ctlCancel.LoadStdImage(IDB_PNG_CANCEL, _T("PNG")); try{ CppSQLite3DB db; db.open(CBoBoDingApp::g_strDatabasePath); CString strSQL=_T(""); strSQL.Format(_T("select * from Account where AccountCode='%s';"),m_strYeWuBianHao); CppSQLite3Query q = db.execQuery(strSQL);//销售单表 //CString strBillCode;; if(!q.eof()) { //销售金额与数量从网格中计算 m_strAccountType=(q.fieldValue(_T("AccountType")));// m_Combo_strXiangMu=q.fieldValue(_T("ProjectName"));// m_strInAmount=(q.fieldValue(_T("InAmount"))); m_strOutAmount=(q.fieldValue(_T("OutAmount"))); m_strAccountDate=(q.fieldValue(_T("AccountDate"))); m_oleDateTime_timeRiQi.ParseDateTime(m_strAccountDate); m_Edit_strBeiZhu=(q.fieldValue(_T("Remark"))); m_Edit_strDanWei=(q.fieldValue(_T("CompanyName"))); } } catch (CppSQLite3Exception& e) { AfxMessageBox(e.errorMessage()); } //UpdateData(FALSE); //UpdateData(TRUE); /*******************************************************************************************/ if (m_strAccountType.Compare(_T("收入"))==0) { m_Edit_strJinE=m_strInAmount; //载入收入的项目名称 m_Static_strJinE=_T("收入金额"); m_Static_strProject=_T("收入项目(必填)"); } else { m_Edit_strJinE=m_strOutAmount; //载入支出的项目名称 m_Static_strJinE=_T("支出金额"); m_Static_strProject=_T("支出项目(必填)"); } /*******************************************************************************************/ try{ CppSQLite3DB db; db.open(CBoBoDingApp::g_strDatabasePath); CString strSQL; strSQL.Format(_T("select * from Project where AccountType='%s';"),m_strAccountType); CppSQLite3Query q = db.execQuery(strSQL);//销售单表 int i=1; CString strProjectName; while (!q.eof()) { strProjectName=q.fieldValue(_T("ProjectName"));//支出项目名称 m_Combo_ctlXiangMu.AddString(strProjectName); q.nextRow(); i++; } } catch (CppSQLite3Exception& e) { //AfxMessageBox(e.errorMessage()); } /*******************************************************************************************/ UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE }
int CPersistencManager::LoadNoticeMap(CCB_MAP ¬ice_map){ if(m_useLevelDB) { leveldb::Status s; leveldb::ReadOptions ro; string value; int mapcount = 0; s = m_LevelDB->Get(ro, NOTICE_MAP_COUNT, &value); if(s.ok()) mapcount = *(int*)value.data(); CLog::Log(LOG_LEVEL_DEBUG, "LoadNoticeMap: %d\n", mapcount); for(int idx = 0; idx < mapcount; idx++) { s = m_LevelDB->Get(ro, NOTICE_MAP_IDX(idx), &value); if(!s.ok()) continue; string comp = value; CLog::Log(LOG_LEVEL_DEBUG, "LoadNoticeMap: comp=%s\n", comp.c_str()); s = m_LevelDB->Get(ro, NOTICE_COUNT(comp.c_str()), &value); if(!s.ok()) continue; int count = *(int*)value.data(); CLog::Log(LOG_LEVEL_DEBUG, "LoadNoticeMap: comp=%s count=%d\n", comp.c_str(), count); for(int i = 0; i < count; i++) { s = m_LevelDB->Get(ro, NOTICE_IDX(comp.c_str(), i), &value); if(!s.ok()) continue; CBlockNotice *pCN = new CBlockNotice(); if (!pCN){ CLog::Log(LOG_LEVEL_ERROR,"Alloc object CBlockNotice Error\n"); continue; } memcpy(pCN, value.data(), sizeof(CBlockNotice)); notice_map[comp].push_back(pCN); } } return 0; } int ret = 0; CCB_MAP::iterator cur_iter; CppSQLite3Query query = m_SQLite3DB.execQuery("select * from Notice"); while (!query.eof()) { CBlockNotice *pCN = new CBlockNotice(); if (!pCN){ CLog::Log(LOG_LEVEL_ERROR,"Alloc object CBlockNotice Error\n"); return -1; } const char* blockid = query.fieldValue("blockid"); memset(pCN->m_guid, 0, sizeof(pCN->m_guid)); memcpy(pCN->m_guid, blockid, strlen(blockid)); pCN->m_status = query.getIntField("status"); string str= query.fieldValue("hostip"); cur_iter = notice_map.find(str); if (cur_iter == notice_map.end()){ CBN_VECTOR cbnlist; cbnlist.push_back(pCN); notice_map[str] = cbnlist; }else{ cur_iter->second.push_back(pCN); } query.nextRow(); } return ret; }
int CPersistencManager::LoadTaskMap(CT_MAP &task_map){ if(m_useLevelDB) { string value; vector<string> allguids; leveldb::ReadOptions ro; leveldb::Status s; int task_count = 0; s = m_LevelDB->Get(ro, TASK_COUNT, &value); if(s.ok()) task_count = *(int*)value.data(); CLog::Log(LOG_LEVEL_DEBUG, "LoadTaskMap: count=%d\n", task_count); for(int i = 1; i <= task_count; i++) { s = m_LevelDB->Get(ro, TASK_IDX(TASK_KEY, i), &value); if(s.ok()) { allguids.push_back(value); } } for(int i = 0; i < allguids.size(); i++) { s = m_LevelDB->Get(ro, allguids[i], &value); if(!s.ok()) continue; //CCrackTask类里面有类,不能直接拷贝构造函数将内存按字节拷贝,咳! CCrackTask* task = (CCrackTask*)value.data(); CCrackTask* pCT = new CCrackTask(); #ifndef USE_PLACEMANT_NEW memcpy(pCT, (crack_task*)task, sizeof(crack_task)); memcpy(pCT->m_owner, task->m_owner, sizeof(task->m_owner)); int len = (char*)&task->m_filelen - (char*)&task->m_status + sizeof(task->m_filelen); memcpy(&pCT->m_status, &task->m_status, len); #else memcpy(pCT, task, sizeof(CCrackTask)); //调用placement new对类成员进行初始化 new (&pCT->m_crackblock_map) CB_MAP(); new (&pCT->cur_crack_block) CB_MAP::iterator(); new (&pCT->m_crackhash_list) CRACK_HASH_LIST(); #endif task_map.insert(CT_MAP::value_type(pCT->guid,pCT)); } return 0; } int ret = 0; CppSQLite3Query query = m_SQLite3DB.execQuery("select * from Task order by 1;"); while (!query.eof()) { CCrackTask *pCT = new CCrackTask(); if (!pCT){ CLog::Log(LOG_LEVEL_ERROR,"Alloc object CCrackTask Error\n"); return -1; } memset(pCT->guid,0,sizeof(pCT->guid)); memcpy(pCT->guid,query.fieldValue("taskid"),strlen(query.fieldValue("taskid"))); pCT->algo = query.getIntField("algo"); pCT->charset = query.getIntField("charset"); pCT->type = query.getIntField("type"); pCT->special = query.getIntField("filetag"); pCT->single = query.getIntField("single"); int len; const unsigned char* info = query.getBlobField("info", len); memcpy(&(pCT->startLength), info, len); memset(pCT->m_owner,0,sizeof(pCT->m_owner)); memcpy(pCT->m_owner,query.fieldValue("owner"),strlen(query.fieldValue("owner"))); pCT->m_status = query.getIntField("status"); pCT->m_split_num = query.getIntField("splitnum"); pCT->m_finish_num = query.getIntField("finishnum"); pCT->m_bsuccess = (strcmp(query.fieldValue("success"),"1") == 0)? true : false; pCT->m_progress = query.getFloatField("progress"); pCT->m_speed = query.getFloatField("speed"); pCT->m_start_time = query.getIntField("starttime"); pCT->m_running_time = query.getIntField("runtime"); pCT->m_remain_time = query.getIntField("remaintime"); pCT->count = query.getIntField("count"); if(pCT->type == bruteforce) CLog::Log(LOG_LEVEL_NOMAL, "[%d %d] %d\n", pCT->startLength, pCT->endLength, pCT->count); else if(pCT->type == dict) CLog::Log(LOG_LEVEL_NOMAL, "[dict=%d] %d\n", pCT->dict_idx, pCT->count); else if(pCT->type == mask) CLog::Log(LOG_LEVEL_NOMAL, "[mask=%s] %d\n", pCT->masks, pCT->count); task_map.insert(CT_MAP::value_type(pCT->guid,pCT)); query.nextRow(); } return ret; }
//必须在task 加载之后 int CPersistencManager::LoadHash(CT_MAP &task_map){ if(m_useLevelDB) { string value; leveldb::ReadOptions ro; leveldb::Status s; for(CT_MAP::iterator it = task_map.begin(); it != task_map.end(); it++) { CCrackTask* pCT = it->second; const char* guid = it->first.c_str(); pCT->m_crackhash_list.resize(pCT->count); //m_crackhash_list是连在一起的,所以必须一次性初始化,详见CCrackTask::SplitTaskFile CCrackHash *pCHs = new CCrackHash[pCT->count]; if (!pCHs){ CLog::Log(LOG_LEVEL_ERROR,"Alloc object CCrackHash Error\n"); return -1; } for(int i = 0; i < pCT->count; i++) { s = m_LevelDB->Get(ro, HASH_KEY(guid, i), &value); if(!s.ok()) continue; CCrackHash* hash = (CCrackHash*)value.data(); CCrackHash* pCH = pCHs + i; *pCH = *hash; pCT->m_crackhash_list[i] = pCH; } } return 0; } int ret = 0; for(CT_MAP::iterator it = task_map.begin(); it != task_map.end(); it++) { const char* guid = it->first.c_str(); CCrackTask *pCT = it->second; char cmd[1024]; _snprintf(cmd, sizeof(cmd), "select * from Hash where taskid='%s'", guid); //必须将容器初始化大小 pCT->m_crackhash_list.resize(pCT->count); //m_crackhash_list是连在一起的,所以必须一次性初始化,详见CCrackTask::SplitTaskFile CCrackHash *pCHs = new (std::nothrow)CCrackHash[pCT->count]; if (!pCHs){ CLog::Log(LOG_LEVEL_ERROR,"Alloc object CCrackHash Error\n"); return -1; } CppSQLite3Query query = m_SQLite3DB.execQuery(cmd); while (!query.eof()) { int tmpIndex = query.getIntField("index0"); CCrackHash *pCH = pCHs + tmpIndex; pCT->m_crackhash_list[tmpIndex] = pCH; memset(pCH->m_john,0,sizeof(pCH->m_john)); memcpy(pCH->m_john,query.fieldValue("john"),strlen(query.fieldValue("john"))); memset(pCH->m_result,0,sizeof(pCH->m_result)); memcpy(pCH->m_result,query.fieldValue("result"),strlen(query.fieldValue("result"))); pCH->m_status = query.getIntField("status"); pCH->m_progress = query.getFloatField("progress"); query.nextRow(); } } return ret; }
BOOL CEditTrainDialog::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here m_ctlIndustryList.InsertColumn(0,""); m_ctlIndustryList.SetColumnWidth(0,186); m_ctlIndustryList.SetExtendedStyle(m_ctlIndustryList.GetExtendedStyle()|LVS_EX_CHECKBOXES); CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB; // // create and preload _TL and _TI // //try { pDB->execDML("DROP TABLE _TL;"); } catch (...) {} //try { pDB->execDML("DROP TABLE _TI;"); } catch (...) {} CString sSQL; sSQL.Format("CREATE TEMP TABLE _TL AS SELECT * FROM Trains_Location WHERE Train_FK=%d;",m_iTrainID); pDB->execDML(sSQL); sSQL.Format("CREATE TEMP TABLE _TI AS SELECT * FROM Trains_Industry WHERE Train_FK=%d;",m_iTrainID); pDB->execDML(sSQL); // CppSQLite3Query q = pDB->execQuery("SELECT id,name FROM Locations;"); // while (!q.eof()) { int nIndex = m_ctlLocationList.AddString(q.fieldValue(1)); m_ctlLocationList.SetItemData(nIndex,atoi(q.fieldValue(0))); q.nextRow(); } q.finalize(); sSQL.Format("SELECT name,trainid FROM Trains WHERE id=%d",m_iTrainID); q = pDB->execQuery(sSQL); if (!q.eof()) { m_sTrainName = q.getStringField(0); m_sTrainCode = q.getStringField(1); } else { m_sTrainName = "Un-named Train"; m_sTrainCode = "ZZZZ"; } q.finalize(); // // get current locations // sSQL.Format("SELECT Trains_Location.Location_FK,Locations.name FROM Trains_Location, Locations WHERE Train_FK=%d AND Locations.id = Trains_Location.Location_FK ORDER BY route_order",m_iTrainID); q = pDB->execQuery(sSQL); while (!q.eof()) { int nIndex = m_ctlRouteLocationList.AddString(q.getStringField("name")); m_ctlRouteLocationList.SetItemData(nIndex,q.getIntField("Location_FK")); // q.nextRow(); } q.finalize(); // m_ctlRemoveButton.EnableWindow(FALSE); m_ctlIndustryList.EnableWindow(FALSE); m_ctlLocalSwitcher.EnableWindow(FALSE); m_ctlDown.EnableWindow(FALSE); m_ctlUp.EnableWindow(FALSE); m_ctlAddButton.EnableWindow(FALSE); m_ctlMaxMovesText.EnableWindow(FALSE); m_ctlMaxMoves.EnableWindow(FALSE); // UpdateData(FALSE); // return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
void CEditTrainDialog::OnOK() { // TODO: Add extra validation here // // insert into Trains_Location / Trains_Industry // (see code in OnCreateButton below) // UpdateData(); // CppSQLite3DB* pDB = &((CTrainOpsApp*)AfxGetApp())->m_pDB; // if( m_iTrainID == -1 ) { // // Convert to Trains, Train_Location, and Train_Industry tables // // If there are not any industries checked, AND there isnt a local switcher checked, // we make a location/location/location route. If there are industries checked, its // an industry-based checklist. All the same to the program, different for the user // // First, create Train table entry, and get the ID // CString sSQL; sSQL.Format("INSERT INTO Trains (trainid,name,Route_FK) VALUES (\"%s\",\"%s\",-1);",m_sTrainCode,m_sTrainName); try { pDB->execDML(sSQL); } catch (...) { sSQL.Format("INSERT INTO Trains (trainid,name) VALUES (\"%s\",\"%s\");",m_sTrainCode,m_sTrainName); pDB->execDML(sSQL); } // sSQL = "SELECT last_insert_rowid()"; CppSQLite3Query q = pDB->execQuery(sSQL); int iTrainID = atoi(q.fieldValue(0)); q.finalize(); // // update _TL and _TI with train ID // sSQL.Format("UPDATE _TI SET Train_FK=%d;",iTrainID); pDB->execDML(sSQL); pDB->execDML("INSERT INTO Trains_Industry SELECT * FROM _TI"); // // Put entries into Train_Location table // for( int i=0;i<m_ctlRouteLocationList.GetCount();i++ ) { int iLocationID = m_ctlRouteLocationList.GetItemData(i); // // local switcher and switch_interchanges for this location // sSQL.Format("SELECT localswitcher,switch_interchanges,max_moves FROM _TL WHERE Location_FK=%d;",iLocationID); CppSQLite3Query q = pDB->execQuery(sSQL); int iLocalSwitcher(0); int iSwitchInterchanges(1); int iMaxMoves(0); if( !q.eof()) { iLocalSwitcher = q.getIntField("localswitcher"); iSwitchInterchanges = q.getIntField("switch_interchanges"); iMaxMoves = q.getIntField("max_moves"); } q.finalize(); // sSQL.Format("INSERT INTO Trains_Location (Train_FK,route_order,Location_FK,localswitcher,switch_interchanges,max_moves) VALUES (%d,%d,%d,%d,%d,%d);",iTrainID,i+1,iLocationID,iLocalSwitcher,iSwitchInterchanges,iMaxMoves); pDB->execDML(sSQL); } // //MessageBox("Train Created!"); } else { // // Delete existing Train_Location and Train_Industry entries for this train // CString sSQL; sSQL.Format("DELETE FROM Trains_Location WHERE Train_FK=%d;",m_iTrainID); pDB->execDML(sSQL); sSQL.Format("DELETE FROM Trains_Industry WHERE Train_FK=%d;",m_iTrainID); pDB->execDML(sSQL); // // Update Routes name and code // sSQL.Format("UPDATE Trains SET trainid=\"%s\" ,name=\"%s\" WHERE id=%d;",m_sTrainCode,m_sTrainName,m_iTrainID); pDB->execDML(sSQL); // // Put entries into Trains_Location and Trains_Industry tables // pDB->execDML("INSERT INTO Trains_Industry SELECT * FROM _TI"); // for( int i=0;i<m_ctlRouteLocationList.GetCount();i++ ) { int iLocationID = m_ctlRouteLocationList.GetItemData(i); // // local switcher and switch interchanges for this location? // sSQL.Format("SELECT localswitcher,switch_interchanges,max_moves FROM _TL WHERE Location_FK=%d;",iLocationID); CppSQLite3Query q = pDB->execQuery(sSQL); int iLocalSwitcher(0); int iSwitchInterchanges(1); int iMaxMoves(0); if( !q.eof()) { iLocalSwitcher = q.getIntField("localswitcher"); iSwitchInterchanges = q.getIntField("switch_interchanges"); iMaxMoves = q.getIntField("max_moves"); } q.finalize(); // sSQL.Format("INSERT INTO Trains_Location (Train_FK,route_order,Location_FK,localswitcher,switch_interchanges,max_moves) VALUES (%d,%d,%d,%d,%d,%d);",m_iTrainID,i+1,iLocationID,iLocalSwitcher,iSwitchInterchanges,iMaxMoves); pDB->execDML(sSQL); } // MessageBox("Train Updated!"); } // try { pDB->execDML("DROP TABLE _TL;"); } catch (...) {} try { pDB->execDML("DROP TABLE _TI;"); } catch (...) {} CDialog::OnOK(); }
//必须在task 加载之后 int CPersistencManager::LoadBlockMap(CB_MAP &block_map,CT_MAP &task_map){ if(m_useLevelDB) { for(CT_MAP::iterator it = task_map.begin(); it != task_map.end(); it++) { const char* guid = it->first.c_str(); CCrackTask* pCT = it->second; leveldb::ReadOptions ro; leveldb::Status s; string value; int actual_num = 0; //连在一起申请,不然在deleteTask函数释放时会出错 CCrackBlock* pCBs = new (std::nothrow)CCrackBlock[pCT->m_split_num]; if (!pCBs){ CLog::Log(LOG_LEVEL_ERROR, "Alloc object %d CCrackBlock Error\n", pCT->m_split_num); return -2; } for(int i = 0; i < pCT->m_split_num; i++) { s = m_LevelDB->Get(ro, BLOCK_IDX(guid, i), &value); if(!s.ok()) continue; s = m_LevelDB->Get(ro, value, &value); if(!s.ok()) continue; actual_num ++; CCrackBlock* item = (CCrackBlock*) value.data(); CCrackBlock *pCB = pCBs + i; *pCB = *item; pCB->task = pCT; pCT->m_crackblock_map.insert(CB_MAP::value_type(pCB->guid,pCB)); block_map.insert(CB_MAP::value_type(pCB->guid, pCB)); } pCT->m_split_num = actual_num; } return 0; } int ret = 0; CT_MAP::iterator cur_iter ; CT_MAP::iterator end_iter = task_map.end(); CCrackTask *pCT = NULL; for(cur_iter = task_map.begin(); cur_iter != end_iter; cur_iter++) { const char* guid = cur_iter->first.c_str(); pCT = cur_iter->second; //连在一起申请,不然在deleteTask函数释放时会出错 CCrackBlock* pCBs = new (std::nothrow)CCrackBlock[pCT->m_split_num]; if (!pCBs){ CLog::Log(LOG_LEVEL_ERROR, "Alloc object %d CCrackBlock Error\n", pCT->m_split_num); return -2; } char cmd[1024]; _snprintf(cmd, sizeof(cmd), "select * from Block where taskid='%s'", guid); CppSQLite3Query query = m_SQLite3DB.execQuery(cmd); int idx = 0; while (!query.eof()) { CCrackBlock *pCB = pCBs + idx; idx ++; memset(pCB->john,0,sizeof(pCB->john)); memset(pCB->m_comp_guid,0,sizeof(pCB->m_comp_guid)); memset(pCB->guid,0,sizeof(pCB->guid)); memcpy(pCB->m_comp_guid,query.fieldValue("compip"),strlen(query.fieldValue("compip"))); memcpy(pCB->guid,query.fieldValue("blockid"),strlen(query.fieldValue("blockid"))); pCB->algo = pCT->algo; pCB->charset = pCT->charset; pCB->type = query.getIntField("type"); int len; const unsigned char* info = query.getBlobField("info", len); memcpy(&(pCB->start), info, len); int tmpIndex = query.getIntField("index0"); pCB->hash_idx = tmpIndex; memcpy(pCB->john,pCT->m_crackhash_list[pCB->hash_idx]->m_john,sizeof(pCT->m_crackhash_list[pCB->hash_idx]->m_john)); pCB->special = pCT->special; pCB->task = pCT; pCB->m_progress = query.getFloatField("progress"); pCB->m_speed = query.getFloatField("speed"); pCB->m_status = query.getIntField("status"); pCB->m_remaintime = query.getIntField("remaintime"); cur_iter->second->m_crackblock_map.insert(CB_MAP::value_type(pCB->guid,pCB)); block_map.insert(CB_MAP::value_type(pCB->guid,pCB)); query.nextRow(); } } return ret; }