I've been learning ADO recently and trying to do a simple SQL Plus, and there are some experiences I'd like to share with you in the process.
The code-run effect is shown below:
Compile-time to specify the correct path in stdafx.h:
#import "Msado15.dll" no_namespace rename ("EOF", "adoeof")
One, the connection database
In this example I have connected 3 common databases: Access,oracle,sql server. Key is the connection character
String, as follows:
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));
}
Second, the acquisition of error messages
An error occurred while connecting or manipulating ADO, and you can get an error message using the _connectionptr object:
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;
}
Number of records to get "update", "Insert" Operation:
_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);