- 下載SQL Server
- 安裝與建立資料庫
- 開啟新專案,以MFC Dialog為例,初始化
AfxOleInit(); //or ::CoInitialize(NULL);
- 引用ADO功能
#import "C:\Program Files (x86)\common files\system\ado\msado15.dll" no_namespace rename("EOF", "ADOEOF") rename("BOF","adoBOF")
因為我電腦同時有32bit和64bit的msado15.dll,所以指明路徑no_namespace - 告訴電腦不要產生其命名空間
rename - 表示需要重新命名,避免dll裡頭的EOF常數關鍵字和AP裡頭的衝突
- 建立連線
try
{
m_pConnection.CreateInstance("ADODB.Connection");
//connect database
_bstr_t strConnect("Provider=SQLOLEDB; Data Source=localhost\\MSSQLSERVER_2012; Integrated Security=SSPI; Database=testDB01;");
m_pConnection->Open(strConnect,"","",NULL);
if(m_pConnection != NULL)
AfxMessageBox(_T("Connet DB success!"));
else return ;
}
catch (_com_error e)
{
CString errormessage;
errormessage.Format(L"Connect DB fail!\r\nMessage:%s",e.ErrorMessage());
AfxMessageBox(errormessage);
return ;
}
- 獲得資料,利用record set
_RecordsetPtr m_pRecordset;
m_pRecordset = m_pConnection->Execute("SELECT * from testTable01",NULL,adCmdText); //透過sql指令抓取全部Table裡頭的資料內容
while(!m_pRecordset->ADOEOF)
{
_variant_t mID, mName, mTel;
mID = m_pRecordset->GetCollect("id");//透過標明列數取值也可以(從第0列開始),如:m_pRecordset->GetCollect(_variant_t((long)0))
mName = m_pRecordset->GetCollect("name");
mTel = m_pRecordset->GetCollect("tel");
m_pRecordset->MoveNext();
}
m_pRecordset->Close();//
我是用表格來呈現抓到的內容,可以看出DB裡頭的資料被我抓出來顯示在表格上了testMSSQL.7z


0 意見:
張貼留言