用ADO编制SQLPlus程序2008-04-20高春我最近正在学习ADO,并试着做了一个简单的SQL Plus,在此过程中有一些经验希望和大家分享。代码运行效果图如下:

编译时要在stdafx.h中指定正确的路径:#import "msado15.dll" no_namespace rename("EOF","adoEOF")一、连接数据库在此例子中我连接了3种常用的数据库:Access,Oracle,Sql server。关键是连接字符串的不同,如下所示:
HRESULT hr;
_ConnectionPtr m_pConnTemp;
UpdateData();
//Oracle 的连接:
CString strConnection = "Provider=MSDAORA;Data Source=" + m_dbserver +
";User ID=" + m_username + "; Password=" + m_passwd;
//Sql server的连接:
CString strConnection = "Provider=SQLOLEDB.1;Data Source=" + m_dbserver +
";Initial Catalog=" + m_initDb + //初始时连接的数据库
";User ID=" + m_username + "; PWD=" + m_passwd;
//Access 的连接:
CString strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
m_filename;
try
{
hr = m_pConnTemp.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
hr=m_pConnTemp->Open((_bstr_t)strConnection,"","",-1);
OnOK();
}
}
catch(_com_error e)
{
CCommon common;
AfxMessageBox(common.DisplayAdoError(m_pConnTemp));
}
二 、错误消息的获得当连接或操作ADO时发生错误,可以利用_ConnectionPtr对象得到错误信息:
CString CCommon::DisplayAdoError(_ConnectionPtr m_pConnection)
{
long errorcount = m_pConnection->GetErrors()->GetCount();
_bstr_t add;
CString ErrorMessage,temp;
for(short i=0; i<errorcount; i++)
{
add = m_pConnection->GetErrors()->GetItem(_variant_t((short)i))->GetDescription();
temp = (char *)add;
ErrorMessage += temp;
}
return ErrorMessage;
}
三、得到"update","insert"操作的记录数:
_variant_t fieldCount;
VariantInit (&fieldCount);
MainFrame->m_pUserSet = MainFrame->m_commandptr->Execute(&fieldCount,NULL,adCmdUnknown);
if(!MainFrame->m_pUserSet ->State) //当是Select操作时此条件为假
{
//fieldCount.lVal中保存的就是"update","insert"操作的记录数
View->ShowResult(fieldCount.lVal);
}
VariantClear(&fieldCount);