_variant_t和_bstr_t这两个类分别封装并管理VARIANT和BSTR这两种数据类型,

VARIANT和BSTR这两种类型是COM中使用的数据类型。

实现_variant_t向int,String ,double,long,byte等类型转换

为了C++中的变量应用到ADO编程中,只能进行数据类型的转换。
通过_variant_t和_bstr_t这两个类,就可

_variant_t var;
var=m_pRecordset->GetCollect ("UserName");
ss=(TCHAR*)(_bstr_t)vUsername;//转换成字符串

以方便的把C++类型变量转换成COM中的变量了。

CString转换为_variant_t:

CString str = _T("xxx");
_variant_t var = (LPCTSTR)str;

把CString 转换为_variant_t:

整型:(long) (_variant_t) m_pRecordset->GetFieldByName("XX");
字符串型:(m_pRecordset->GetFieldByName("XX")).bstrVal;

把一个日期字符串转成_variant_t:

.CString可以直接转_variant_t。
CString szTime("2008-8-8 08:08:08");
_variant_t mt = szTime;
._variant_t转CString用如下函数:
CString VariantToCString(_variant_t var)
{ CString str; //转换以后的字符串 switch(var.vt) {
case VT_BSTR: //var is BSTR type str=var.bstrVal; break;
case VT_I2: //var is short int type str.Format("%d",(int)var.iVal); break;
case VT_I4: //var is long int type str.Format("%d",var.lVal); break;
case VT_R4: //var is float type str.Format(".6f",(double)var.fltVal); break;
case VT_R8: //var is double type str.Format(".6f",var.dblVal); break;
case VT_CY: //var is CY type str=COleCurrency(var).Format(); break;
case VT_DATE: //var is DATE type str=COleDateTime(var).Format(); break;
case VT_BOOL: //var is VARIANT_BOOL str= (var.boolVal==) ?L"FALSE": L"TRUE"; break;
default: str.Format("Unk type %d\n",var.vt); TRACE("Unknown type %d\n",var.vt); } return str; }

把一个int转换为_variant_t类型:

int a = ;
_variant_t var; var = (_variant_t)(long)a;

_variant_t和_bstr_t-LMLPHP

     UpdateData();
CString strCmd = L"select * from n where 材料='";
strCmd += m_Querymaterial;
strCmd += "'";
m_pRecordset = m_pConnection->Execute(_bstr_t(strCmd), &RecordsAffected, adCmdText);

_variant_t和_bstr_t-LMLPHP

_variant_t vM,vN;
try
{
while(!m_pRecordset->adoEOF)
{
//取得第0列的值,从0开始计数
vM=m_pRecordset->GetCollect(_variant_t((long)));
//取得“折射率”这一列的值
vN=m_pRecordset->GetCollect("折射率");
CString strtemp;
if (vM.vt!=VT_NULL)
{
strtemp.Format(_T("%s"),vM.lVal);
}
if (vN.vt!=VT_NULL)
{
strtemp+=" ";
strtemp+=(LPCTSTR)(_bstr_t)vN;
}
m_list1.AddString(strtemp);
m_list1.AddString(_T("\n"));
m_pRecordset->MoveNext();//移动到下一条记录
}
}
catch(_com_error &e)
{
AfxMessageBox(e.Description());
return;
}
if (m_pRecordset->Close())
{
m_pRecordset->Close();
m_pRecordset=NULL;
}
if (m_pConnection->State)
{
m_pConnection->Close();
m_pConnection=NULL;
}
}
05-28 08:16