20141208-用VC++連結MS-SQL DB,從安裝SQL Server 2012開始

最近要幫朋友公司寫一個內部的簡單查詢系統,由於沒有實做過VC++去連結SQL Server,所以趁著昨天抓一些工具和看資料來寫一下Demo,熟悉一下環境。順便把步驟給記起來。
  • 下載SQL Server
去微軟網站下載「SQLEXPRADV_x86_CHT.exe」。這個檔案包含全部所需元件和工具,一般選擇安裝這一個。在下載的時候還有其他不同檔案,可以讓使用者自行選擇。我選擇32bit的安裝。
  • 安裝與建立資料庫
安裝完之後開啟「SQL Server Management Studio」,建立DB和Table,連線方式選擇Windows驗證。這裡我用資料庫名稱為「testDB01」,建立的Table名稱為「testTable01」,隨意用「insert into」指令添加2筆資料。裡頭有3個欄位,id,name以及tel。至此資料庫簡易的準備階段完成。
  • 開啟新專案,以MFC Dialog為例,初始化
首先,要初始化OLE的動作,在「InitInstance() 」function中加上這段code
AfxOleInit();
//or
::CoInitialize(NULL);
  • 引用ADO功能
在「stdafx.h」檔案裡頭做import「msado15.dll」的動作,可以讓開發者使用ADO(ActiveX Data Objects)
#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裡頭的衝突
  • 建立連線
連線字串中,Integrated Security表示用Windows認證連線的,所以不用輸入使用者帳號密碼登入。Database這個字也可以用Initial Catalog,兩者意義相同,是資料庫名稱。
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裡頭的資料被我抓出來顯示在表格上了


--完整Source Code(VC++ 2008 vaildated)--
testMSSQL.7z

0 意見:

搜尋此網誌

總網頁瀏覽量

TK呱呱

Made with by TK