예제 #1
0
파일: BrainMemory.cpp 프로젝트: GMIS/GMIS
void   CBrainMemory::SetSystemItem(int64 Item,AnsiString Info){
	CppSQLite3Buffer SQL;
	CppSQLite3Query  Result;
	char a[30],b[30];
     int64toa(ROOM_SYSTEM,a);
	 int64toa(Item,b);

    SQL.format("select b from \"%s\" where a = \"%s\";",a,b);				
	Result = BrainDB.execQuery(SQL);
	bool Find = !Result.eof();
    Result.finalize();

	if(!Find){
		SQL.format("insert into \"%s\" values (\"%s\", ?)",
			a,
			b);
	}else{
		SQL.format("update \"%s\" set b = ? where a = \"%s\";",
			a,
			b
			);
	}

	CppSQLite3Statement State = BrainDB.compileStatement(SQL);
	State.bind(1,Info.c_str()); //替换第一个问号
	State.execDML();

}
예제 #2
0
void CVoxSQLite::InsertContact( Contact& rContact )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO Contact "
						 "( [username], [nickname], [merged_parent_username]) "
						 "VALUES( ?, ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

//		stmt.bind( 1, rContact.getName().c_str()	);
//		stmt.bind( 2, rContact.getNickname().c_str());
//		stmt.bind( 3, rContact.getMergedContact().c_str() );

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nContactId = (int)m_db.lastRowId();

//		InsertGroups	    ( rContact.getName().c_str(), rContact.getGroups()			);
//		InsertMergedContacts( rContact.getName().c_str(), rContact.getMergedContacts()	);
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
예제 #3
0
void CVoxSQLite::InsertGroup( const char* username, Group& rGroup )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO [Group] "
						 "( [username], [name] ) "
						 "VALUES( ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, username );
		stmt.bind( 2, rGroup.getName() );

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nId = (int)m_db.lastRowId();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
BOOL DatabaseModule_Impl::sqlInsertOrReplaceGroupInfoEntity(IN const module::GroupInfoEntity& groupInfo)
{
	try
	{
		CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertGroupInfoSql.c_str());
		stmt.bind(1, groupInfo.gId.c_str());
		stmt.bind(2, util::cStringToString(groupInfo.csName).c_str());
		stmt.bind(3, util::cStringToString(groupInfo.desc).c_str());
		stmt.bind(4, groupInfo.avatarUrl.c_str());
		stmt.bind(5, groupInfo.creatorId.c_str());
		stmt.bind(6, int(groupInfo.type));
		stmt.bind(7, int(groupInfo.version));
		stmt.bind(8, int(groupInfo.groupUpdated));
		stmt.bind(9, int(groupInfo.shieldStatus));
		std::string& strJson = _makeJsonForGroupMembers(groupInfo.groupMemeberList);
		stmt.bind(10, strJson.c_str());
		stmt.execDML();
	}
	catch (CppSQLite3Exception& sqliteException)
	{
#ifdef _DEBUG
		MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
		CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
		LOG__(ERR, _T("insert failed,error msg:%s"), csErrMsg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		return FALSE;
	}

	return TRUE;
}
BOOL DatabaseModule_Impl::sqlDeleteGroupInfoEntity(IN const std::string& groupId)
{
	try
	{
		CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(deleteGroupInfoSql.c_str());
		stmt.bind(1, groupId.c_str());
		stmt.execDML();
	}
	catch (CppSQLite3Exception& sqliteException)
	{
#ifdef _DEBUG
		MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
		CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
		LOG__(ERR, _T("delete failed,error msg:%s"), csErrMsg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		return FALSE;
	}

	return TRUE;
}
예제 #6
0
void CVoxSQLite::InsertStreetAddress( int nId, StreetAddress& addr )
{
	std::string	strSql = "INSERT INTO StreetAddress "
		"( [profile_id], [type], [street], [locality], [region], [postcode], [country], [visibility] ) "
						 "VALUES( ?, ?, ?, ?, ?, ?, ?, ? ); ";

	try
	{
		//TODO: compile as a member var?
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, nId	);
		stmt.bind( 2, addr.getType().c_str()		);
		stmt.bind( 3, addr.getStreet1().c_str() 	);
		stmt.bind( 4, addr.getCity().c_str()		);
		stmt.bind( 5, addr.getStateProvince().c_str());
		stmt.bind( 6, addr.getPostalCode().c_str()	);
		stmt.bind( 7, addr.getCountry().c_str()		);
		stmt.bind( 8, (int) addr.getVisibility()	);

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
예제 #7
0
void CVoxSQLite::InsertUrl ( int nId, const std::string& type, const std::string& url, EnumVisibility::Visibility vis )
{
	if ( IsValidUrl( url.c_str() ) )
	{
		std::string	strSql = "INSERT INTO Url "
			"( [profile_id], [type], [url], [visibility] ) "
							 "VALUES( ?, ?, ?, ? ); ";

		try
		{
			//TODO: compile as a member var?
			CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

			stmt.bind( 1, nId			);
			stmt.bind( 2, type.c_str()	);
			stmt.bind( 3, url.c_str()   );
			stmt.bind( 4, (int)vis		);

			stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
			stmt.reset();
		}

		catch (CppSQLite3Exception& e)
		{
			e.errorCode();
		}
	}
}
BOOL DatabaseModule_Impl::sqlUpdateRecentSessionInfoEntity(IN const module::SessionEntity& sessionInfo)
{
	try
	{
		CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(updateRecentSessionByIdSql.c_str());
		stmt.bind(1, sessionInfo.sessionID.c_str());
		stmt.bind(2, int(sessionInfo.sessionType));
		stmt.bind(3, int(sessionInfo.updatedTime));
		stmt.bind(4, int(sessionInfo.latestmsgId));
		stmt.bind(5, sessionInfo.latestMsgContent.c_str());
		stmt.bind(6, sessionInfo.latestMsgFromId.c_str());

		stmt.bind(7, sessionInfo.sessionID.c_str());
		int countUpdate = stmt.execDML();
		if (0 == countUpdate)
		{
			return FALSE;
		}
	}
	catch (CppSQLite3Exception& sqliteException)
	{
#ifdef _DEBUG
		MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
		CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
		LOG__(ERR, _T("db failed,error msg:%s"), csErrMsg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		return FALSE;
	}
	return TRUE;
}
예제 #9
0
void CVoxSQLite::InsertMergedContact( const char* strContactUsername, const char* strUsername )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO [MergedContact] "
						 "( [parent_username], [username] ) "
						 "VALUES( ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, strContactUsername );
		stmt.bind( 2, strUsername );

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nId = (int)m_db.lastRowId();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
예제 #10
0
int CppSQLite3DB::insertBlob(const CString& szSQL, const unsigned char *data, int dataLength)
{
    CppSQLite3Statement statement = compileStatement(szSQL);

    statement.bind(1, data, dataLength);

    return statement.execDML();
}
BOOL DatabaseModule_Impl::sqlBatchInsertGroupInfos(IN module::GroupInfoMap& mapGroupInfos)
{
	try
	{
		CppSQLite3Statement stmtBegin = m_pSqliteDB->compileStatement(BeginInsert.c_str());
		stmtBegin.execDML();

		for (auto kv : mapGroupInfos)
		{
			module::GroupInfoEntity& groupInfo = kv.second;
			CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertGroupInfoSql.c_str());
			stmt.bind(1, groupInfo.gId.c_str());
			stmt.bind(2, util::cStringToString(groupInfo.csName).c_str());
			stmt.bind(3, util::cStringToString(groupInfo.desc).c_str());
			stmt.bind(4, groupInfo.avatarUrl.c_str());
			stmt.bind(5, groupInfo.creatorId.c_str());
			stmt.bind(6, int(groupInfo.type));
			stmt.bind(7, int(groupInfo.version));
			stmt.bind(8, int(groupInfo.groupUpdated));
			stmt.bind(9, int(groupInfo.shieldStatus));
			std::string& strJson = _makeJsonForGroupMembers(groupInfo.groupMemeberList);
			stmt.bind(10, strJson.c_str());
			stmt.execDML();
		}

		CppSQLite3Statement stmtEnd = m_pSqliteDB->compileStatement(EndInsert.c_str());
		stmtEnd.execDML();
	}
	catch (CppSQLite3Exception& e)
	{
		CString csErrMsg = util::stringToCString(e.errorMessage());
		LOG__(ERR, _T("batch insert failed,error msg:%s"), csErrMsg);
		CppSQLite3Statement stmtRollback = m_pSqliteDB->compileStatement(RollBack.c_str());
		stmtRollback.execDML();
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("batch insert unknown exception"));
		return FALSE;
	}

	return TRUE;
}
예제 #12
0
int CppSQLite3DB::updateBlob(const CString& szTableName, const CString& szFieldName, const unsigned char* data, int dataLength, const CString& szWhere)
{

    CString sql = CString("update ") + szTableName + " set " + szFieldName + "=? where " + szWhere;

    CppSQLite3Statement statement = compileStatement(sql);
    statement.bind(1, data, dataLength);

    return statement.execDML();
}
예제 #13
0
//##ModelId=474D30760272
bool CClip_ImportExport::ExportToSqliteDB(CppSQLite3DB &db)
{
	bool bRet = false;
	try
	{
		//Add to Main Table
		m_Desc.Replace(_T("'"), _T("''"));
		db.execDMLEx(_T("insert into Main values(NULL, %d, '%s');"), CURRENT_EXPORT_VERSION, m_Desc);
		long lId = (long)db.lastRowId();

		//Add to Data table
		CClipFormat* pCF;
		CppSQLite3Statement stmt = db.compileStatement(_T("insert into Data values (NULL, ?, ?, ?, ?);"));

		for(int i = m_Formats.GetSize()-1; i >= 0 ; i--)
		{
			pCF = & m_Formats.ElementAt(i);

			stmt.bind(1, lId);
			stmt.bind(2, GetFormatName(pCF->m_cfType));
			long lOriginalSize = GlobalSize(pCF->m_hgData);
			stmt.bind(3, lOriginalSize);

			const unsigned char *Data = (const unsigned char *)GlobalLock(pCF->m_hgData);
			if(Data)
			{
				//First compress the data
				long lZippedSize = compressBound(lOriginalSize);
				Bytef *pZipped = new Bytef[lZippedSize];
				if(pZipped)
				{				
					int nZipReturn = compress(pZipped, (uLongf *)&lZippedSize, (const Bytef *)Data, lOriginalSize);
					if(nZipReturn == Z_OK)
					{
						stmt.bind(4, pZipped, lZippedSize);
					}

					delete []pZipped;
					pZipped = NULL;
				}
			}
			GlobalUnlock(pCF->m_hgData);

			stmt.execDML();
			stmt.reset();

			m_Formats.RemoveAt(i);
		}

		bRet = true;
	}
	CATCH_SQLITE_EXCEPTION_AND_RETURN(false)

	return bRet;
}
BOOL DatabaseModule_Impl::sqlBatchInsertRecentSessionInfos(IN std::vector<module::SessionEntity>& sessionList)
{
	try
	{
		CppSQLite3Statement stmtBegin = m_pSqliteDB->compileStatement(BeginInsert.c_str());
		stmtBegin.execDML();

		for (module::SessionEntity sessionInfo : sessionList)
		{
			CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertRecentSessionSql.c_str());
			stmt.bind(1, sessionInfo.sessionID.c_str());
			stmt.bind(2, int(sessionInfo.sessionType));
			stmt.bind(3, int(sessionInfo.updatedTime));
			stmt.bind(4, int(sessionInfo.latestmsgId));
			stmt.bind(5, sessionInfo.latestMsgContent.c_str());
			stmt.bind(6, sessionInfo.latestMsgFromId.c_str());
			stmt.execDML();
		}

		CppSQLite3Statement stmtEnd = m_pSqliteDB->compileStatement(EndInsert.c_str());
		stmtEnd.execDML();
	}
	catch (CppSQLite3Exception& e)
	{
		CString csErrMsg = util::stringToCString(e.errorMessage());
		LOG__(ERR, _T("batch insert failed,error msg:%s"), csErrMsg);
		CppSQLite3Statement stmtRollback = m_pSqliteDB->compileStatement(RollBack.c_str());
		stmtRollback.execDML();
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("batch insert unknown exception"));
		return FALSE;
	}
	return TRUE;
}
예제 #15
0
/** Message Queuing.
 *
 * @param szId          Sensor ID
 * @param nMessageId    사용자 정의 Message ID
 * @param nMessageType  Message Type (0x01 Immediately, 0x02 Lazy, 0x03 Passive)
 * @param nDuration     Lazy, Passive 일 경우 유지 시간(sec)
 * @param nErrorHandler Error Handler
 * @param nPreHandler   Pre-Action Handler
 * @param nPostHandler  Post-Action Handler
 * @param nUserData     User Data
 * @param nDataLength   Message length
 * @param pszData       Message
 *
 */
BOOL CMessageHelper::Add(const char *szId, UINT nMessageId, BYTE nMessageType, UINT nDuration,
        UINT nErrorHandler, UINT nPreHandler, UINT nPostHandler, UINT nUserData, int nDataLength, const BYTE *pszData)
{
    int i=1;
    if(!CheckDB()) return FALSE;

    if(!Open()) return FALSE;
    try
    {
        CppSQLite3Statement stmt = m_SqliteHelper.compileStatement(
            "INSERT INTO MessageTbl "
            "( targetId, messageId, messageType, duration, "
            "  errorHandler, preHandler, postHandler, userData, payload ) "
            "VALUES "
            "( ?, ?, ?, ?, "
            "  ?, ?, ?, ?, ?);");

        stmt.bind(i, szId);                             i++;
        stmt.bind(i, (const int)nMessageId);            i++;
        stmt.bind(i, nMessageType);                     i++;
        stmt.bind(i, (const int)nDuration);             i++;
        stmt.bind(i, (const int)nErrorHandler);         i++;
        stmt.bind(i, (const int)nPreHandler);           i++;
        stmt.bind(i, (const int)nPostHandler);          i++;
        stmt.bind(i, (const int)nUserData);             i++;
        stmt.bind(i, pszData, nDataLength);             i++;

        stmt.execDML();
        stmt.finalize();

        Close();
        return TRUE;
    }
	catch ( CppSQLite3Exception& e )
	{
        Close();
		XDEBUG(ANSI_COLOR_RED "DB ERROR: %d %s\r\n" ANSI_NORMAL, e.errorCode(), e.errorMessage());
	}

    return FALSE;
}
BOOL DatabaseModule_Impl::sqlUpdateGroupInfoEntity(std::string& sId, IN const module::GroupInfoEntity& groupInfo)
{
	try
	{
		//"update groupinfo set name=?,desc=?,avatarUrl=?,creatorId=?,type=?,version=?,lastUpdateTime=?,shieldStatus=?,memberlist=? where groupId=?";
		CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(updateGroupInfoBySIdSql.c_str());
		stmt.bind(1, util::cStringToString(groupInfo.csName).c_str());
		stmt.bind(2, util::cStringToString(groupInfo.desc).c_str());
		stmt.bind(3, groupInfo.avatarUrl.c_str());
		stmt.bind(4, groupInfo.creatorId.c_str());
		stmt.bind(5, int(groupInfo.type));
		stmt.bind(6, int(groupInfo.version));
		stmt.bind(7, int(groupInfo.groupUpdated));
		stmt.bind(8, int(groupInfo.shieldStatus));
		std::string& strJson = _makeJsonForGroupMembers(groupInfo.groupMemeberList);
		stmt.bind(9, strJson.c_str());
		stmt.bind(9, groupInfo.gId.c_str());
		int countUpdate = stmt.execDML();
		if (0 == countUpdate)
		{
			LOG__(ERR, _T("db update failed:%s"), util::stringToCString(groupInfo.gId));
			return FALSE;
		}
	}
	catch (CppSQLite3Exception& sqliteException)
	{
#ifdef _DEBUG
		MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
		CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
		LOG__(ERR, _T("db failed,error msg:%s"), csErrMsg);
		return FALSE;
	}
	catch (...)
	{
		return FALSE;
	}

	return TRUE;
}
예제 #17
0
void CVoxSQLite::InsertProfile( const char* username, Profile& rProfile )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO Profile "
						 "( [username], [first_name], [last_name], [alias], [sms_signature], [company], [notes], [sex] ) "
//						 "[birthday], [photo] ) "		//TODO
						 "VALUES( ?, ?, ?, ?, ?, ?, ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, username	);
		stmt.bind( 2, rProfile.getFirstName().c_str()	);
		stmt.bind( 3, rProfile.getLastName().c_str() 	);
		stmt.bind( 4, rProfile.getAlias().c_str()		);
		stmt.bind( 5, rProfile.getSmsSignature().c_str());
		stmt.bind( 6, rProfile.getCompany().c_str()		);
		stmt.bind( 7, rProfile.getNotes().c_str()		);
		stmt.bind( 8, rProfile.getSex()					);
//		stmt.bind( 10, rProfile.getBirthday()			);
//		stmt.bind( 11, rProfile.getPhoto()				);

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nId = (int)m_db.lastRowId();

		InsertUrls			 ( nId, rProfile.getUrls()			  );
		InsertStreetAddresses( nId, rProfile.getStreetAddresses() );
		InsertEmailAddresses ( nId, rProfile.getEmailAddresses()  );
		InsertTelephones	 ( nId, rProfile.getTelephones()	  );
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
BOOL DatabaseModule_Impl::sqlInsertFileTransferHistory(IN TransferFileEntity& fileInfo)
{
    if (fileInfo.nClientMode == IM::BaseDefine::ClientFileRole::CLIENT_OFFLINE_UPLOAD
        || fileInfo.nClientMode == IM::BaseDefine::ClientFileRole::CLIENT_REALTIME_SENDER)
    {
        LOG__(DEBG, _T("fileInfo.nClientMode not fixed"));
        return FALSE;
    }
    try
    {
        CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertFileTransferHistorySql.c_str());
        stmt.bind(1, fileInfo.sTaskID.c_str());
        stmt.bind(2, fileInfo.sFromID.c_str());
        std::string filename = util::cStringToString(fileInfo.getRealFileName());
        stmt.bind(3, filename.c_str());
        std::string savePath = util::cStringToString(fileInfo.getSaveFilePath());
        stmt.bind(7, savePath.c_str());
        stmt.bind(8, (Int32)fileInfo.nFileSize);
        stmt.bind(9, time(0));
        stmt.execDML();
    }

    catch (CppSQLite3Exception& sqliteException)
    {
#ifdef _DEBUG
        MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
        CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
        LOG__(ERR, _T("failed,error msg:%s"), csErrMsg);
        return FALSE;
    }
    catch (...)
    {
        LOG__(ERR, _T("unknown exception"));
        return FALSE;
    }

    return TRUE;
}
예제 #19
0
/** 해당 ID에 대한 전체 Message 삭제
 */
BOOL CMessageHelper::Delete(const char *szId, BYTE nMessageType)
{
    if(!CheckDB()) return FALSE;

    if(!Open()) return FALSE;
    try
    {
        CppSQLite3Statement stmt;
        
        if(nMessageType > 0)
        {
            stmt = m_SqliteHelper.compileStatement(
                "DELETE FROM MessageTbl "
                "WHERE targetId = ? AND messageType = ? ; ");

            stmt.bind(1, szId);
            stmt.bind(2, nMessageType);
        } else {
            stmt = m_SqliteHelper.compileStatement(
                "DELETE FROM MessageTbl "
                "WHERE targetId = ?; ");

            stmt.bind(1, szId);
        }

        stmt.execDML();
        stmt.finalize();
        Close();
    }
	catch ( CppSQLite3Exception& e )
	{
        Close();
		XDEBUG(ANSI_COLOR_RED "DB ERROR DELETE: %d %s\r\n" ANSI_NORMAL, e.errorCode(), e.errorMessage());
        return FALSE;
    }
    return TRUE;
}
예제 #20
0
//插入任务
int CPersistencManager::PersistTask(const CCrackTask *pCT, Action action)
{
	if(m_useLevelDB)
	{
		leveldb::Status s;
		leveldb::WriteOptions wo;
		leveldb::ReadOptions ro;
		string value;
		wo.sync = false;

		if(action == Insert)
		{
			int task_count = 0;
			s = m_LevelDB->Get(ro, TASK_COUNT, &value);
			if(s.ok())
				task_count = *(int*)value.data();
			task_count ++;

			s = m_LevelDB->Put(wo, TASK_COUNT, leveldb::Slice((char*)&task_count, sizeof(task_count)));

			s = m_LevelDB->Put(wo, TASK_IDX(TASK_KEY, task_count), pCT->guid);

			s = m_LevelDB->Put(wo, pCT->guid, leveldb::Slice((char*)pCT, sizeof(CCrackTask)));
		}
		else if(action == Update)
		{
			s = m_LevelDB->Put(wo, pCT->guid, leveldb::Slice((char*)pCT, sizeof(CCrackTask)));
		}
		else if(action == Delete)
		{
			s = m_LevelDB->Delete(wo, pCT->guid);
		}

		return 0;
	}

	char cmd[1024];
	
	try{
		if(action == Insert)
		{
			sprintf(cmd,"insert into Task values('%s',%d,%d,%d,%d,%d,?,'%s',%d,%d,%d,%d,%f,%f,%d,%d,%d,%d)",
				pCT->guid,pCT->algo,pCT->charset,pCT->type,pCT->special,pCT->single,pCT->m_owner,
				pCT->m_status,pCT->m_split_num,pCT->m_finish_num,pCT->m_bsuccess,pCT->m_progress,pCT->m_speed,pCT->m_start_time,
				pCT->m_running_time,pCT->m_remain_time,pCT->count);
			CppSQLite3Statement statement = m_SQLite3DB.compileStatement(cmd);
			
			unsigned char* blob = (unsigned char*)&(pCT->startLength);
			int len = pCT->filename - blob;
			statement.bind(1, blob, len);
			statement.execDML();
		}
		else if(action == Update)
		{
			sprintf(cmd,"update Task set status=%d,count=%d,splitnum=%d,success=%d,finishnum=%d, "
						"progress=%f,speed=%f,starttime=%d,runtime=%d where taskid='%s'",
						pCT->m_status, pCT->count, pCT->m_split_num, pCT->m_bsuccess, pCT->m_finish_num,
						pCT->m_progress, pCT->m_speed, pCT->m_start_time, pCT->m_running_time, pCT->guid);
			m_SQLite3DB.execDML(cmd);
		}
		else if(action == Delete)
		{
			sprintf(cmd,"delete from Task where taskid='%s'", pCT->guid);
			m_SQLite3DB.execDML(cmd);
		}
	}catch(CppSQLite3Exception& ex){
		CLog::Log(LOG_LEVEL_WARNING,"Failed to [Action=%d] task %s: %s\n", action, pCT->guid, ex.errorMessage());
		return -1;
	}
	return 0;
}
예제 #21
0
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;
    }
    
}
예제 #22
0
int Maxthon3PlugIn::ImportFavoriteData( PFAVORITELINEDATA pData, int32& nDataNum )
{
	if (pData == NULL || nDataNum == 0)
	{
		return ERROR_INVALID_PARAM;
	}

	#define MAX_BUFFER_LEN	4096

	CppSQLite3DB  m_SqliteDatabase;
	wchar_t szInsert[MAX_BUFFER_LEN] = {0};
	wchar_t szDelete[MAX_BUFFER_LEN] = {0};

	if (m_pMemFavoriteDB != NULL)
	{
		m_SqliteDatabase.openmem(m_pMemFavoriteDB, "");

		int i = 0;

		m_SqliteDatabase.execDML(StringHelper::UnicodeToUtf8(L"delete from MyFavNodes where parent_id <> ''").c_str());

		m_SqliteDatabase.execDML("begin transaction");

		for (int i = 0; i < nDataNum; i++)
		{
			if (pData[i].bDelete == true)
			{
				continue;
			}

			swprintf_s(szInsert, MAX_BUFFER_LEN-1, L"insert into MyFavNodes"
				L"(id,parent_id,type,title,url,most_fav,visit_count,norder,add_date,shortcut)"
				L" values(?,?,%d,?,?,0,0,%d,%d,0)",
				pData[i].bFolder == true ? IT_FOLDER : IT_URL,
				pData[i].nOrder,
				(int32)pData[i].nAddTimes);

			CppSQLite3Statement sqliteStatement = m_SqliteDatabase.compileStatement(StringHelper::UnicodeToANSI(szInsert).c_str());

			std::string strTemp1 = StringHelper::StringToHex(
				StringHelper::ANSIToUnicode(CMD5Checksum::GetMD5((BYTE *)&pData[i].nId, sizeof(int32))));
			sqliteStatement.bind(1, (unsigned char *)strTemp1.c_str(), strTemp1.length());

			if (pData[i].nPid == 0)
			{
				unsigned char szParentNode[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

				sqliteStatement.bind(2, szParentNode, 16);
			}
			else
			{
				strTemp1 = StringHelper::StringToHex(StringHelper::ANSIToUnicode(
					CMD5Checksum::GetMD5((BYTE *)&pData[i].nPid, sizeof(int32))).c_str());
				sqliteStatement.bind(2, (unsigned char *)strTemp1.c_str(), strTemp1.length());
			}

			sqliteStatement.bind(3, (unsigned char *)pData[i].szTitle, (wcslen(pData[i].szTitle) + 1) * sizeof(wchar_t));
			sqliteStatement.bind(4, (unsigned char *)pData[i].szUrl, (wcslen(pData[i].szUrl) + 1) * sizeof(wchar_t));

			sqliteStatement.execDML();
			sqliteStatement.reset();
		}
		m_SqliteDatabase.execDML("commit transaction");

		SaveDatabase();
		return ERROR_OK;
	}

	return ERROR_SQLITE_ERROR;
}
예제 #23
0
int main(int argc, char** argv)
{
    try
    {
		int row;
        CppSQLite3DB db;

        cout << "SQLite Header Version: " << CppSQLite3DB::SQLiteHeaderVersion() << endl;
        cout << "SQLite Library Version: " << CppSQLite3DB::SQLiteLibraryVersion() << endl;
        cout << "SQLite Library Version Number: " << CppSQLite3DB::SQLiteLibraryVersionNumber() << endl;

        remove(gszFile);
        db.open(gszFile);

        ////////////////////////////////////////////////////////////////////////////////
        // Demonstrate getStringField(), getIntField(), getFloatField()
        ////////////////////////////////////////////////////////////////////////////////
        db.execDML("create table parts(no int, name char(20), qty int, cost number);");
        db.execDML("insert into parts values(1, 'part1', 100, 1.11);");
        db.execDML("insert into parts values(2, null, 200, 2.22);");
        db.execDML("insert into parts values(3, 'part3', null, 3.33);");
        db.execDML("insert into parts values(4, 'part4', 400, null);");

        cout << endl << "CppSQLite3Query getStringField(), getIntField(), getFloatField() tests" << endl;
        CppSQLite3Query q = db.execQuery("select * from parts;");
        while (!q.eof())
        {
            cout << q.getIntField(0) << "|";
            cout << q.getStringField(1) << "|";
            cout << q.getInt64Field(2) << "|";
            cout << q.getFloatField(3) << "|" << endl;
            q.nextRow();
        }

        cout << endl << "specify NULL values tests" << endl;
        q = db.execQuery("select * from parts;");
        while (!q.eof())
        {
            cout << q.getIntField(0) << "|";
            cout << q.getStringField(1, "NULL") << "|";
            cout << q.getIntField(2, -1) << "|";
            cout << q.getFloatField(3, -3.33) << "|" << endl;
            q.nextRow();
        }

        cout << endl << "Specify fields by name" << endl;
        q = db.execQuery("select * from parts;");
        while (!q.eof())
        {
            cout << q.getIntField("no") << "|";
            cout << q.getStringField("name") << "|";
            cout << q.getInt64Field("qty") << "|";
            cout << q.getFloatField("cost") << "|" << endl;
            q.nextRow();
        }

        cout << endl << "specify NULL values tests" << endl;
        q = db.execQuery("select * from parts;");
        while (!q.eof())
        {
            cout << q.getIntField("no") << "|";
            cout << q.getStringField("name", "NULL") << "|";
            cout << q.getIntField("qty", -1) << "|";
            cout << q.getFloatField("cost", -3.33) << "|" << endl;
            q.nextRow();
        }
		q.finalize();

		////////////////////////////////////////////////////////////////////////////////
        // Demonstrate getStringField(), getIntField(), getFloatField()
		// But this time on CppSQLite3Table
        ////////////////////////////////////////////////////////////////////////////////
        cout << endl << "CppSQLite3Table getStringField(), getIntField(), getFloatField() tests" << endl;
        CppSQLite3Table t = db.getTable("select * from parts;");
        for (row = 0; row < t.numRows(); row++)
        {
            t.setRow(row);
            cout << t.getIntField(0) << "|";
            cout << t.getStringField(1) << "|";
            cout << t.getIntField(2) << "|";
            cout << t.getFloatField(3) << "|" << endl;
        }

        cout << endl << "specify NULL values tests" << endl;
        for (row = 0; row < t.numRows(); row++)
        {
            t.setRow(row);
            cout << t.getIntField(0, -1) << "|";
            cout << t.getStringField(1, "NULL") << "|";
            cout << t.getIntField(2, -1) << "|";
            cout << t.getFloatField(3, -3.33) << "|" << endl;
        }

        cout << endl << "Specify fields by name" << endl;
        for (row = 0; row < t.numRows(); row++)
        {
            t.setRow(row);
            cout << t.getIntField("no") << "|";
            cout << t.getStringField("name") << "|";
            cout << t.getIntField("qty") << "|";
            cout << t.getFloatField("cost") << "|" << endl;
        }

        cout << endl << "specify NULL values tests" << endl;
        for (row = 0; row < t.numRows(); row++)
        {
            t.setRow(row);
            cout << t.getIntField("no") << "|";
            cout << t.getStringField("name", "NULL") << "|";
            cout << t.getIntField("qty", -1) << "|";
            cout << t.getFloatField("cost", -3.33) << "|" << endl;
        }


		////////////////////////////////////////////////////////////////////////////////
		// Demonstrate multi-statement DML
		// Note that number of rows affected is only from the last statement
		// when multiple statements are used
		////////////////////////////////////////////////////////////////////////////////
        cout << endl << "Multi-Statement execDML()" << endl;
		const char* szDML = "insert into parts values(5, 'part5', 500, 5.55);"
							"insert into parts values(6, 'part6', 600, 6.66);"
							"insert into parts values(7, 'part7', 700, 7.77);";
		int nRows = db.execDML(szDML);
		cout << endl << nRows << " rows affected" << endl;
        cout << db.execScalar("select count(*) from parts;") << " rows in parts table" << endl;
		            szDML = "delete from parts where no = 2;"
							"delete from parts where no = 3;";
		nRows = db.execDML(szDML);
        cout << endl << nRows << " rows affected" << endl;
        cout << db.execScalar("select count(*) from parts;") << " rows in parts table" << endl;


		////////////////////////////////////////////////////////////////////////////////
		// Demonstrate new typing system & BLOBS
		// ANy data can be stored in any column
		////////////////////////////////////////////////////////////////////////////////
        cout << endl << "Data types and BLOBs()" << endl;
        db.execDML("create table types(no int, "
				"name char(20), qty float, dat blob);");
        db.execDML("insert into types values(null, null, null, null);");
        db.execDML("insert into types values(1, 2, 3, 4);");
        db.execDML("insert into types values(1.1, 2.2, 3.3, 4.4);");
        db.execDML("insert into types values('a', 'b', 'c', 'd');");

        CppSQLite3Statement stmt = db.compileStatement("insert into types values(?,?,?,?);");
        unsigned char buf[256];
		memset(buf, 1, 1); stmt.bind(1, buf, 1);
		memset(buf, 2, 2); stmt.bind(2, buf, 2);
		memset(buf, 3, 3); stmt.bind(3, buf, 3);
		memset(buf, 4, 4); stmt.bind(4, buf, 4);
		stmt.execDML();
        cout << db.execScalar("select count(*) from types;") << " rows in types table" << endl;

        q = db.execQuery("select * from types;");
        while (!q.eof())
        {
			for (int i = 0; i < q.numFields(); i++)
			{
				switch (q.fieldDataType(i))
				{
				case SQLITE_INTEGER  : cout << "SQLITE_INTEGER|"; break;
				case SQLITE_FLOAT    : cout << "SQLITE_FLOAT  |"; break;
				case SQLITE_TEXT     : cout << "SQLITE_TEXT   |"; break;
				case SQLITE_BLOB     : cout << "SQLITE_BLOB   |"; break;
				case SQLITE_NULL     : cout << "SQLITE_NULL   |"; break;
				default: cout << "***UNKNOWN TYPE***"; break;
				}
			}
            q.nextRow();
			cout << endl;
        }

        nRows = db.execDML("delete from types where no = 1 or no = 1.1 or no = 'a' or no is null;");
		cout << endl << nRows << " rows deleted, leaving binary row only" << endl;

        q = db.execQuery("select * from types;");
		const unsigned char* pBlob;
		int nLen;
		pBlob = q.getBlobField(0, nLen);
		cout << "Field 1 BLOB length: " << nLen << endl;
		pBlob = q.getBlobField(1, nLen);
		cout << "Field 2 BLOB length: " << nLen << endl;
		pBlob = q.getBlobField(2, nLen);
		cout << "Field 3 BLOB length: " << nLen << endl;
		pBlob = q.getBlobField(3, nLen);
		cout << "Field 4 BLOB length: " << nLen << endl;

		q.finalize();

        nRows = db.execDML("delete from types;");
		cout << endl << nRows << " rows deleted, leaving empty table" << endl;
        unsigned char bin[256];

        for (int i = 0; i < sizeof bin; i++)
        {
            bin[i] = i;
        }

        stmt = db.compileStatement("insert into types values(?,0,0,0);");
		stmt.bind(1, bin, sizeof bin);
		stmt.execDML();

        cout << "Stored binary Length: " << sizeof bin << endl;

        q = db.execQuery("select * from types;");

		pBlob = q.getBlobField(0, nLen);
		cout << "Field 1 BLOB length: " << nLen << endl;

        for (i = 0; i < sizeof bin; i++)
        {
            if (pBlob[i] != i)
            {
				cout << "Problem: i: ," << i << " BLOB[i]: " << pBlob[i] << endl;
            }
        }
	}
    catch (CppSQLite3Exception& e)
    {
        cerr << e.errorCode() << ":" << e.errorMessage() << endl;
    }

	////////////////////////////////////////////////////////////////////////////////
    // Loop until user enters q or Q
    ////////////////////////////////////////////////////////////////////////////////
    char c(' ');

    while (c != 'q' && c != 'Q')
    {
        cout << "Press q then enter to quit: ";
        cin >> c;
    }
    return 0;
}
BOOL DatabaseModule_Impl::sqlInsertMessage(IN MessageEntity& msg)
{
	if (module::TCPCLIENT_STATE_DISCONNECT == module::getTcpClientModule()->getTcpClientNetState()
		|| MESSAGE_RENDERTYPE_SYSTEMTIPS == msg.msgRenderType)
	{
		return FALSE;
	}
	if (msg.msgId <= 0)
	{
		std::string msgDecrptyCnt;
		DECRYPT_MSG(msg.content, msgDecrptyCnt);
		LOG__(ERR, _T("msgid <= 0, msgid:%d msg_content:%s Don't save to DB!")
			, msg.msgId, util::stringToCString(msgDecrptyCnt));
		return FALSE;
	}

	try
	{
		CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertMessageSql.c_str());
		stmt.bind(1, (Int32)msg.msgId);
		stmt.bind(2, msg.sessionId.c_str());
		stmt.bind(3, msg.talkerSid.c_str());
		//对语音消息做个特殊处理,content存储的是json格式字符串
		if (MESSAGE_RENDERTYPE_AUDIO == msg.msgRenderType)
		{
			Json::Value root;
			root["msgAudioTime"] = msg.msgAudioTime;
			root["msgAudioId"] = msg.content;
			Json::FastWriter fstWrite;
			std::string audioContent = fstWrite.write(root);
			stmt.bind(4, audioContent.c_str());
		}
		else
		{
			stmt.bind(4, msg.content.c_str());
		}
		stmt.bind(5, msg.msgRenderType);
		stmt.bind(6, msg.msgSessionType);
		stmt.bind(7, (Int32)msg.msgTime);
		stmt.bind(8, time(0));
		stmt.execDML();
	}

	catch (CppSQLite3Exception& sqliteException)
	{
#ifdef _DEBUG
		//MessageBoxA(0, sqliteException.errorMessage(), "BD ERROR", MB_OK | MB_ICONHAND);
#endif
		CString csErrMsg = util::stringToCString(sqliteException.errorMessage(), CP_UTF8);
		LOG__(ERR, _T("db failed,error msg:%s"), csErrMsg);
		_msgToTrace(msg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		_msgToTrace(msg);
		return FALSE;
	}

	return TRUE;
}
예제 #25
0
EXPORT_C gint32 CContactDb::UpdateEntity(CDbEntity * pEntity)
	{
	int i;
	char sql[256] = {0};
	OpenDatabase();
	
	try 
		{
		m_dbBeluga.execDML("begin transaction;");
		/* update contact entity */
		strcpy(sql, "update contact set "); 
		for (i=1; i<ContactField_EndFlag; i++)
			{
			GString * fieldName = (GString*)g_ptr_array_index(m_pFieldsName, i);
			strcat(sql, fieldName->str);
			strcat(sql, " = ?");
			if (i != ContactField_EndFlag - 1)
				strcat(sql, ", ");
			}
		strcat(sql, "where cid = ?;");
		
		CppSQLite3Statement statement = m_dbBeluga.compileStatement(sql);

		GString * idValue = NULL;
		if (ECode_No_Error == pEntity->GetFieldValue(0, &idValue))
		{
			statement.bind(ContactField_EndFlag, idValue->str);
			g_string_free(idValue, TRUE);
		}
		else
			statement.bindNull(ContactField_EndFlag);

		for (i=1; i<ContactField_EndFlag; i++)
			{
			GString * fieldValue = NULL;
			if (ECode_No_Error == pEntity->GetFieldValue(i, &fieldValue))
				{
				statement.bind(i, fieldValue->str);
				g_string_free(fieldValue, TRUE);
				}
			else
				statement.bindNull(i);
			}
		statement.execDML();
		statement.reset();
		
		/* update contact_ext entity */
		CContact * contact = (CContact*)pEntity;
		GString * fieldValue = NULL;
		contact->GetFieldValue(ContactField_Type, &fieldValue);
		if (ContactType_Phone == atoi(fieldValue->str))
			{
			CPhoneContact * phonecontact = (CPhoneContact*)pEntity;
			GString * fieldId = NULL;
			phonecontact->GetFieldValue(ContactField_Id, &fieldId);
			memset(sql, 0, sizeof(sql));
			sprintf(sql, "delete from contact_ext where cid = %d;", atoi(fieldId->str));
			m_dbBeluga.execDML(sql);
			
			/* insert phones */
			GHashTable * phones = NULL;
			phonecontact->GetAllPhones(&phones);
			g_hash_table_foreach(phones, update_contact_ext_row, phonecontact);
			g_hash_table_destroy(phones);
			
			/* insert emails */
			GHashTable * emails = NULL;
			phonecontact->GetAllEmails(&emails);
			g_hash_table_foreach(emails, update_contact_ext_row, phonecontact);
			g_hash_table_destroy(emails);
			
			/* insert ims */
			GHashTable * ims = NULL;
			phonecontact->GetAllIMs(&ims);
			g_hash_table_foreach(ims, update_contact_ext_row, phonecontact);
			g_hash_table_destroy(ims);
			
			/* insert addresses */
			GPtrArray * addresses = NULL;
			phonecontact->GetAllAddresses(&addresses);
			for (guint32 j=0; j<addresses->len; j++)
				{
				memset(sql, 0, sizeof(sql));
				stAddress * addr = (stAddress*)g_ptr_array_index(addresses, j);
				sprintf(sql, "insert into address values(NULL, %d, '%s', '%s', '%s', '%s', '%s', '%s');", 
									addr->atype, addr->block, addr->street, addr->district,
									addr->city, addr->state, addr->country, addr->postcode);
									
				guint32 nAddrId = m_dbBeluga.execScalar("select max(aid) from address;");
				memset(sql, 0, sizeof(sql));
				sprintf(sql, "insert into contact_ext values(NULL, %d, %d, %d);", 
									atoi(fieldId->str), addr->atype, nAddrId);
				m_dbBeluga.execDML(sql);
				}
			freeAddressArray(addresses);
			g_string_free(fieldId, TRUE);
			}
		g_string_free(fieldValue, TRUE);
		
		m_dbBeluga.execDML("commit transaction;");
		delete pEntity;
		pEntity = NULL;
		CloseDatabase();
		return 0;
		}
	catch(CppSQLite3Exception& e)
		{
		m_dbBeluga.execDML("rollback transaction;");
		delete pEntity;
		pEntity = NULL;
		CloseDatabase();
		return ERROR(ESide_Client, EModule_Db, ECode_Update_Failed);
		}
		
	return 0;
	}
BOOL DatabaseModule_Impl::sqlBatchInsertMessage(IN std::list<MessageEntity>& msgList)
{
	if (module::TCPCLIENT_STATE_DISCONNECT == module::getTcpClientModule()->getTcpClientNetState())
	{
		LOG__(ERR, _T("TCPCLIENT_STATE_DISCONNECT"));
		return FALSE;
	}
	if (msgList.empty())
	{
		LOG__(ERR, _T("msgList is empty!"));
		return FALSE;
	}
	MessageEntity msg;
	try
	{
		CppSQLite3Statement stmtBegin = m_pSqliteDB->compileStatement(BeginInsert.c_str());
		stmtBegin.execDML();

		std::list<MessageEntity>::iterator iter = msgList.begin();
		for (; iter != msgList.end(); ++iter)
		{
			MessageEntity msg = *iter;
			if (msg.msgId <= 0)//非法的msg消息不用存储
			{
				std::string msgDecrptyCnt;
				DECRYPT_MSG(msg.content,msgDecrptyCnt);
				LOG__(ERR, _T("msgid <= 0, msgid:%d msg_content:%s Don't save to DB!")
					, msg.msgId, util::stringToCString(msgDecrptyCnt));
				continue;
			}
			CppSQLite3Statement stmt = m_pSqliteDB->compileStatement(insertMessageSql.c_str());
			stmt.bind(1, (Int32)msg.msgId);
			stmt.bind(2, msg.sessionId.c_str());
			stmt.bind(3, msg.talkerSid.c_str());
			//对语音消息做个特殊处理,content存储的是json格式字符串
			if (MESSAGE_RENDERTYPE_AUDIO == msg.msgRenderType)
			{
				Json::Value root;
				root["msgAudioTime"] = msg.msgAudioTime;
				root["msgAudioId"] = msg.content;
				Json::FastWriter fstWrite;
				std::string audioContent = fstWrite.write(root);
				stmt.bind(4, audioContent.c_str());
			}
			else
			{
				stmt.bind(4, msg.content.c_str());
			}
			stmt.bind(5, msg.msgRenderType);
			stmt.bind(6, msg.msgSessionType);
			stmt.bind(7, (Int32)msg.msgTime);
			stmt.bind(8, time(0));
			stmt.execDML();
		}

		CppSQLite3Statement stmtEnd = m_pSqliteDB->compileStatement(EndInsert.c_str());
		stmtEnd.execDML();
	}
	catch (CppSQLite3Exception& e)
	{
		CString csErrMsg = util::stringToCString(e.errorMessage());
		LOG__(ERR, _T("db failed,error msg:%s"), csErrMsg);
		CppSQLite3Statement stmtRollback = m_pSqliteDB->compileStatement(RollBack.c_str());
		stmtRollback.execDML();
		_msgToTrace(msg);
		return FALSE;
	}
	catch (...)
	{
		LOG__(ERR, _T("db unknown exception"));
		_msgToTrace(msg);
		return FALSE;
	}

	return TRUE;
}
예제 #27
0
//插入一个任务的所有workitem
int CPersistencManager::PersistBlockMap(const CB_MAP& block_map, Action action){

	CB_MAP::const_iterator begin_block = block_map.begin();
	CB_MAP::const_iterator end_block = block_map.end();
	CB_MAP::const_iterator block_iter;
	
	if(m_useLevelDB)
	{
		leveldb::WriteOptions wo;
		wo.sync = false;
		leveldb::Status s;

		if(action == Insert)
		{
			std::map<string, int> mymap;
			for(block_iter = begin_block;block_iter!=end_block;block_iter++)
			{
				CCrackBlock* pCB = block_iter->second;
				char* taskguid = pCB->task->guid;

				s = m_LevelDB->Put(wo, BLOCK_IDX(taskguid, mymap[taskguid]++), pCB->guid);
					
				s = m_LevelDB->Put(wo, pCB->guid, leveldb::Slice((char*)pCB, sizeof(CCrackBlock)));
			}
		}
		else if(action == Update)
		{
			for(block_iter = begin_block;block_iter!=end_block;block_iter++)
			{
				CCrackBlock* pCB = block_iter->second;
				s = m_LevelDB->Put(wo, pCB->guid, leveldb::Slice((char*)pCB, sizeof(CCrackBlock)));
			}
		}
		else if(action == Delete)
		{
			std::map<string, int> mymap;
			for(block_iter = begin_block;block_iter!=end_block;block_iter++)
			{
				CCrackBlock* pCB = block_iter->second;
				char* taskguid = pCB->task->guid;

				s = m_LevelDB->Delete(wo, BLOCK_IDX(taskguid, mymap[taskguid]++));
				s = m_LevelDB->Delete(wo, pCB->guid);
			}
		}

		return 0;
	}

	int ret = 0;
	CCrackBlock *pCB = NULL;
	char cmd[1024];

	if(action == Insert)
	{
		for(block_iter = begin_block;block_iter!=end_block;block_iter++){

			pCB = block_iter->second;
			sprintf(cmd,"insert into Block values ('%s','%s', %d, %d, ?, %d, %f, %f, %d, '%s', %d, %d)",
				pCB->guid,pCB->task->guid, pCB->type, pCB->hash_idx, pCB->m_status, pCB->m_progress,
				pCB->m_speed,pCB->m_remaintime, pCB->m_comp_guid, pCB->m_starttime, pCB->m_finishtime);

			try{
				CppSQLite3Statement statement = m_SQLite3DB.compileStatement(cmd);			
				unsigned char* blob = (unsigned char*)&(pCB->start);
				int len = (unsigned char*)&(pCB->task) - blob;
				statement.bind(1, blob, len);
				statement.execDML();
			} catch(CppSQLite3Exception& ex){
				CLog::Log(LOG_LEVEL_WARNING,"Failed to Insert block %s: %s\n", pCB->guid, ex.errorMessage());
			}
		}
	}
	else if(action == Update)
	{
		for(block_iter = begin_block;block_iter!=end_block;block_iter++)
		{
			CCrackBlock* pCB = block_iter->second;
			UpdateOneBlock(pCB);
		}
	}
	else if(action == Delete)
	{
		if(begin_block != end_block)
		{
			pCB = begin_block->second;
			sprintf(cmd,"delete from Block where taskid='%s'", pCB->task->guid);

			try{
				m_SQLite3DB.execDML(cmd);
			}catch(CppSQLite3Exception& ex){
				CLog::Log(LOG_LEVEL_WARNING,"Failed to delete block %s: %s\n", pCB->guid, ex.errorMessage());
			}
		}
	}


	return ret;
}