MFC 中ADO鏈結sql server 資料庫

2021-08-03 22:14:46 字數 1742 閱讀 1072

一.mfc中ado鏈結資料庫通常有四個步驟

(1)引入ado檔案

(2)初始化ole/com庫檔案

(3)利用connection物件連線資料

(4)利用建立好的鏈結,通過connection,command物件執行sql命令,或者利用recordset物件取得結果進行查詢和處理

1.引入ado檔案

#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("eof","adoeof")

為了避免衝突將常數eof改名為adoeof  並且上述預編譯指令不能放在stdafx.h檔案的開頭  應該放在所有include的後面

2.初始化ole/com庫環境::coinitialize(null) 在使用完後要用::couninitialize()釋放

也可以用afxoleinit()函式初始化  但是在使用完成後對於m_precordset不需要釋放  系統會自動釋放  不然的話會崩潰哦(親身經歷)

搞了好長時間都找不到原因  偶爾在網上看到才得以解決  只想說小細節但問題

3.利用connection物件連線資料(對sql server 鏈結資料庫的幾種不同的方式)

_connectionptr m_pconnection;

m_pconnection.createinstance(_uuidof(connection));

try 

(1)cstring strsql="provider=sqloledb;

integrated security=sspi;

persist security info=false;

initial catalog=student;

data source=.";

m_pconnection->open((_bstr_t)strsql,"","",admodeunknown);

(2)cstring strsql="provider=sqloledb;//和上述方法相同 只是去掉了幾個引數而已  這裡對於引數不明白 望各路大神指教

integrated security=sspi;

persist security info=false;

initial catalog=student;

data source=.";

m_pconnection->open((_bstr_t)strsql,"","",admodeunknown);

(3)m_pconnection->open("driver=;server=172.16.49.44;database=student;uid=sa;pwd=123",

"","",

admodeunknown);

catch(_com_error e)

4.利用recordset開啟記錄集並取得資料

_recordsetptr m_precordset;

m_precordset.createinstance (_uuidof(recordset));

trycatch(_com_error *e)

_variant_t var;

cstring str;

for(int i=0; !m_precordset->adoeof; i++)

m_precordset->addnew();

m_precordset->putcollect("studentid",_variant_t(m_strnum));

MFC使用ado鏈結資料庫,及資料庫操作

首先在stdafx.cpp中新增 connectionptr m pconnection commandptr m pcommand recordsetptr m precordset 然後在stdafx.h中的 endif下面新增 import c program files common fil...

MFC通過ADO連線SQL SERVER資料庫

以乙個mfc的dialog應用程式為例。1.首先是引入msado15.dll。在stdafx.h中加入 import c program files common files system ado msado15.dll no namespace rename eof adoeof 2.初始化com...

MFC使用ADO連線SQL Server資料庫

1.首先,要用 import語句來引用支援ado的元件型別庫 tlb 其中型別庫可以作為可執行程式 dll exe等 的一部分被定位在其自身程式中的附屬資源裡,如 被定位在msado15.dll的附屬資源中,只需要直接用 import引用它既可。可以直接在stdafx.h檔案中加入下面語句來實現 i...