⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dictionary.cpp

📁 这个程序主要是在WinCE环境下开发访问SQLCE数据库程序的例子程序
💻 CPP
📖 第 1 页 / 共 2 页
字号:
	//
	hr = CoCreateInstance(	CLSID_SQLSERVERCE_3_0, 
							0, 
							CLSCTX_INPROC_SERVER, 
							IID_IDBInitialize, 
							(void**)&pIDBInitialize);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Initialize a property with name of database
	//
	dbprop[0].dwPropertyID		= DBPROP_INIT_DATASOURCE;
	dbprop[0].dwOptions			= DBPROPOPTIONS_REQUIRED;
	dbprop[0].vValue.vt			= VT_BSTR;
	dbprop[0].vValue.bstrVal	= SysAllocString(m_dictname);
	if(NULL == dbprop[0].vValue.bstrVal)
	{
		hr = E_OUTOFMEMORY;
		goto Exit;
	}

	// Initialize the property set
	//
	dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
	dbpropset[0].rgProperties	 = dbprop;
	dbpropset[0].cProperties	 = sizeof(dbprop)/sizeof(dbprop[0]);

	// Get IDBDataSourceAdmin interface
	//
	hr = pIDBInitialize->QueryInterface(IID_IDBDataSourceAdmin, (void **) &pIDBDataSourceAdmin);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Create and initialize data store
	//
	hr = pIDBDataSourceAdmin->CreateDataSource(1, dbpropset, NULL, IID_IUnknown, &pIUnknownSession);
	if(FAILED(hr))	
    {
		goto Exit;
    }

    // Get IDBCreateSession interface
    //
  	hr = pIDBInitialize->QueryInterface(IID_IDBCreateSession, (void**)&m_pIDBCreateSession);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Get IDBCreateCommand interface
	//
	hr = pIUnknownSession->QueryInterface(IID_IDBCreateCommand, (void**)&pIDBCrtCmd);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Create a command object
	//
	hr = pIDBCrtCmd->CreateCommand(NULL, IID_ICommandText, (IUnknown**)&pICmdText);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Drop "Employees" table if it exists ignoring errors
	//
	ExecuteSQL(pICmdText, (LPWSTR)L"DROP TABLE YF_DICT");

	// Create Employees table
	//
	hr = ExecuteSQL(pICmdText, (LPWSTR)L"CREATE TABLE YF_DICT(Nick NVARCHAR(30), Word NVARCHAR(30))");
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Create Index
	// Note: The sample table has small amount of demo data, the index is created here.
	// In your application, to improve performance, index shoule be created after 
	// inserting initial data. 
	//
	hr = ExecuteSQL(pICmdText, (LPWSTR)L"CREATE INDEX PK_Dict_Nick on YF_DICT(Nick ASC)");
	if(FAILED(hr))
	{
		goto Exit;
	}


Exit:
    // Clear Variant
    //
	VariantClear(&dbprop[0].vValue);

	// Release interfaces
	//
	if(pICmdText)
	{
		pICmdText->Release();
	}

	if(pIDBCrtCmd)
	{
		pIDBCrtCmd->Release();
	}

	if(pIUnknownSession)
	{
		pIUnknownSession->Release();
	}

	if(pIDBDataSourceAdmin)
	{
		pIDBDataSourceAdmin->Release();
	}

	if(pIDBInitialize)
	{
		pIDBInitialize->Release();
	}

	return hr;
}

// 执行脚本
HRESULT CDictionary::ExecuteSQL(ICommandText * pICmdText, WCHAR * pwszQuery)
{
	HRESULT hr = NOERROR;

	hr = pICmdText->SetCommandText(DBGUID_SQL, pwszQuery); 
	if(FAILED(hr))
	{
		goto Exit;
	}

	hr = pICmdText->Execute(NULL, IID_NULL, NULL, NULL, NULL);

Exit:

	return hr;
}

// 初始化内存数组
HRESULT CDictionary::InitDictWord(void)
{
	HRESULT					hr					= NOERROR;			// Error code reporting
	DBID				    TableID;								// Used to open/create table
	DBID				    IndexID;								// Used to open/create index
	DBPROPSET			    rowsetpropset[1];						// Used when opening integrated index
	DBPROP				    rowsetprop[1];							// Used when opening integrated index
	DBBINDING				*prgBinding			= NULL;				// Binding used to create accessor
	HROW				    rghRows[1];								// Array of row handles obtained from the rowset object
	HROW*				    prghRows			= rghRows;			// Row handle(s) pointer
   	ULONG				    cRowsObtained;							// Number of rows obtained from the rowset object
	BYTE					*pData				= NULL;				// Record data
	DBCOLUMNINFO			*pDBColumnInfo		= NULL;				// Record column metadata
	DWORD					dwIndex				= 0;
	DWORD					dwOffset			= 0;
	DWORD					dwBindingSize		= 0;
	DWORD					dwOrdinal			= 0;
	ULONG					ulNumCols			= 0;
	WCHAR					*pStringsBuffer		= NULL;

	IOpenRowset				*pIOpenRowset		= NULL;				// Provider Interface Pointer
	IRowset					*pIRowset			= NULL;				// Provider Interface Pointer
	IColumnsInfo			*pIColumnsInfo		= NULL;				// Provider Interface Pointer
	IAccessor*			    pIAccessor			= NULL;				// Provider Interface Pointer
	HACCESSOR			    hAccessor			= DB_NULL_HACCESSOR;// Accessor handle

	WCHAR*					pwszDict[]		=	{				// Info to retrieve employee names
														L"Nick",
														L"Word"
													 };

    VariantInit(&rowsetprop[0].vValue);

	// Validate IDBCreateSession interface
	//
	if (NULL == m_pIDBCreateSession)
	{
		hr = E_POINTER;
		goto Exit;
	}

    // Create a session object 
    //
    hr = m_pIDBCreateSession->CreateSession(NULL, IID_IOpenRowset, (IUnknown**) &pIOpenRowset);
    if(FAILED(hr))
    {
        goto Exit;
    }

	// Set up information necessary to open a table 
	// using an index and have the ability to seek.
	//
	TableID.eKind			= DBKIND_NAME;
	TableID.uName.pwszName	= (WCHAR*)L"YF_DICT";

	IndexID.eKind			= DBKIND_NAME;
	IndexID.uName.pwszName	= L"PK_Dict_Nick";

	// Request ability to use IRowsetIndex interface
	rowsetpropset[0].cProperties	= 1;
	rowsetpropset[0].guidPropertySet= DBPROPSET_ROWSET;
	rowsetpropset[0].rgProperties	= rowsetprop;

	rowsetprop[0].dwPropertyID		= DBPROP_IRowsetIndex;
	rowsetprop[0].dwOptions			= DBPROPOPTIONS_REQUIRED;
	rowsetprop[0].colid				= DB_NULLID;
	rowsetprop[0].vValue.vt			= VT_BOOL;
	rowsetprop[0].vValue.boolVal	= VARIANT_TRUE;

	// Open the table using the index
	//
	hr = pIOpenRowset->OpenRowset(NULL, 
								  &TableID, 
								  &IndexID, 
								  IID_IRowset, 
								  sizeof(rowsetpropset)/sizeof(rowsetpropset[0]),
								  rowsetpropset, 
								  (IUnknown**)&pIRowset);
	if(FAILED(hr))
	{
		goto Exit;
	}

    // Get IColumnsInfo interface
	//
    hr = pIRowset->QueryInterface(IID_IColumnsInfo, (void **)&pIColumnsInfo);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Get the column metadata 
	//
    hr = pIColumnsInfo->GetColumnInfo(&ulNumCols, &pDBColumnInfo, &pStringsBuffer);
	if(FAILED(hr) || 0 == ulNumCols)
	{
		goto Exit;
	}

    // Create a DBBINDING array.
	//
	dwBindingSize = sizeof(pwszDict)/sizeof(pwszDict[0]);
	prgBinding = (DBBINDING*)CoTaskMemAlloc(sizeof(DBBINDING)*dwBindingSize);
	if (NULL == prgBinding)
	{
		hr = E_OUTOFMEMORY;
		goto Exit;
	}

	// Set initial offset for binding position
	//
	dwOffset = 0;

	// Prepare structures to create the accessor
	//
    for (dwIndex = 0; dwIndex < dwBindingSize; ++dwIndex)
    {
		if (!GetColumnOrdinal(pDBColumnInfo, ulNumCols, pwszDict[dwIndex], &dwOrdinal))
		{
			hr = E_FAIL;
			goto Exit;
		}

		prgBinding[dwIndex].iOrdinal	= dwOrdinal;
		prgBinding[dwIndex].dwPart		= DBPART_VALUE | DBPART_STATUS | DBPART_LENGTH;
		prgBinding[dwIndex].obLength	= dwOffset;                                     
		prgBinding[dwIndex].obStatus	= prgBinding[dwIndex].obLength + sizeof(ULONG);  
		prgBinding[dwIndex].obValue		= prgBinding[dwIndex].obStatus + sizeof(DBSTATUS);
		prgBinding[dwIndex].wType		= pDBColumnInfo[dwOrdinal].wType;
		prgBinding[dwIndex].pTypeInfo	= NULL;
		prgBinding[dwIndex].pObject		= NULL;
		prgBinding[dwIndex].pBindExt	= NULL;
		prgBinding[dwIndex].dwMemOwner	= DBMEMOWNER_CLIENTOWNED;
		prgBinding[dwIndex].dwFlags		= 0;
		prgBinding[dwIndex].bPrecision	= pDBColumnInfo[dwOrdinal].bPrecision;
		prgBinding[dwIndex].bScale		= pDBColumnInfo[dwOrdinal].bScale;

		switch(prgBinding[dwIndex].wType)
		{
		case DBTYPE_WSTR:		
			prgBinding[dwIndex].cbMaxLen = sizeof(WCHAR)*(pDBColumnInfo[dwOrdinal].ulColumnSize + 1);	// Extra buffer for null terminator 
			break;
		default:
			prgBinding[dwIndex].cbMaxLen = pDBColumnInfo[dwOrdinal].ulColumnSize; 
			break;
		}

		// Calculate the offset, and properly align it
		// 
		dwOffset = prgBinding[dwIndex].obValue + prgBinding[dwIndex].cbMaxLen;
		dwOffset = ROUND_UP(dwOffset, COLUMN_ALIGNVAL);
	}

	// Get IAccessor 
	//
	hr = pIRowset->QueryInterface(IID_IAccessor, (void**)&pIAccessor);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Create the accessor
	//
	hr = pIAccessor->CreateAccessor(DBACCESSOR_ROWDATA, 
									dwBindingSize, 
									prgBinding, 
									0, 
									&hAccessor, 
									NULL);
	if(FAILED(hr))
	{
		goto Exit;
	}

	// Allocate data buffer.
	//
	pData = (BYTE*)CoTaskMemAlloc(dwOffset);
	if (NULL == pData)
	{
		hr = E_OUTOFMEMORY;
		goto Exit;
	}

	// Retrive a row
	//
	hr = pIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained, &prghRows);
	while (SUCCEEDED(hr) && DB_S_ENDOFROWSET != hr)
	{
		// Set data buffer to zero
		//
		memset(pData, 0, dwOffset);

		// Fetch actual data
		hr = pIRowset->GetData(prghRows[0], hAccessor, pData);
		if (FAILED(hr))
		{
			// Release the rowset.
			//
			pIRowset->ReleaseRows(1, prghRows, NULL, NULL, NULL);
			goto Exit;
		}

		// If return a null value, ignore the contents of the value and length parts of the buffer.
		//
		if (DBSTATUS_S_ISNULL != *(DBSTATUS *)(pData+prgBinding[0].obStatus))
		{
			// If return a null value, ignore the contents of the value and length parts of the buffer.
			//
			if (DBSTATUS_S_ISNULL != *(DBSTATUS *)(pData+prgBinding[1].obStatus))
			{
				_tcscpy(m_pData[ m_wordcount ].wordFromLang, W2T((WCHAR*)(pData+prgBinding[0].obValue)));
				_tcscpy(m_pData[ m_wordcount ].wordToLang, W2T((WCHAR*)(pData+prgBinding[1].obValue)));
				m_wordcount ++;
			}
		}

		// Release the rowset.
		//
		hr = pIRowset->ReleaseRows(1, prghRows, NULL, NULL, NULL);
		if(FAILED(hr))
		{
			goto Exit;
		}


		// Fetches next row.
		if ( m_wordcount >= MaxWordCount )
		{
			_tprintf(_T("Read to-word string exceed max wordcount!"));
		}
		hr = pIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained, &prghRows);
	}

Exit:
    // Clear Variants
    //
	VariantClear(&rowsetprop[0].vValue);

  
    // Free allocated DBBinding memory
    //
    if (prgBinding)
    {
        CoTaskMemFree(prgBinding);
        prgBinding = NULL;
    }

    // Free allocated column info memory
    //
    if (pDBColumnInfo)
    {
        CoTaskMemFree(pDBColumnInfo);
        pDBColumnInfo = NULL;
    }
	
	// Free allocated column string values buffer
    //
    if (pStringsBuffer)
    {
        CoTaskMemFree(pStringsBuffer);
        pStringsBuffer = NULL;
    }

    // Free data record buffer
    //
	if (pData)
	{
        CoTaskMemFree(pData);
		pData = NULL;
	}

	// Release interfaces
	//
	if(pIAccessor)
	{
		pIAccessor->ReleaseAccessor(hAccessor, NULL); 
		pIAccessor->Release();
	}

	if (pIColumnsInfo)
	{
		pIColumnsInfo->Release();
	}

	if(pIRowset)
	{
		pIRowset->Release();
	}

	if(pIOpenRowset)
	{
		pIOpenRowset->Release();
	}

	return hr;
}


BOOL CDictionary::GetColumnOrdinal(DBCOLUMNINFO* pDBColumnInfo, DWORD dwNumCols, WCHAR* pwszColName, DWORD* pOrdinal)
{
	for(DWORD dwCol = 0; dwCol< dwNumCols; ++dwCol)
	{
		if(NULL != pDBColumnInfo[dwCol].pwszName)
		{
			if(0 == _wcsicmp(pDBColumnInfo[dwCol].pwszName, pwszColName))
			{
				*pOrdinal = pDBColumnInfo[dwCol].iOrdinal;
				return TRUE;
			}
		}
	}

	return FALSE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -