準備:# W$ Z7 l9 s v- h
(1)、引入ADO類
#import "c:\program files\common files\system\ado\msado15.dll" \7 |6 o: Q! I5 g9 J. [9 n* K
no_namespace \
rename ("EOF", "adoEOF")
(2)、初始化COM
在MFC中可以用AfxOleInit();非MFC環境中用:6 w! v+ y( t) F, [
CoInitialize(NULL);1 ^* Y1 U- N2 I: p
CoUnInitialize();" R% c# u5 E( t3 h9 J( @
(3)#import 包含后就可以用3個智能指針了:_ConnectionPtr、_RecordsetPtr和_CommandPtr$ v; A! h( `# w3 ^' b
1.連接和關閉數據庫 (1)連接
例子:連接Access數據庫
AfxOleInit();//初始化1 M3 O; D+ W/ x( m* ]( _9 p
HRESULT hr;% u7 e$ O! y5 X6 S L2 \
try( Y( t3 A% \) Q1 Q
{% a; V8 C6 }' U
hr = m_pConnection.CreateInstance("ADODB.Connection");///創建Connection對象
if(SUCCEEDED(hr))- S1 j7 e! p0 T7 a
{
m_pConnection->ConnectionTimeout = 0;" d4 G7 k: e# A( X+ F
hr = m_pConnection->Open( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb", "", "", adModeUnknown);
//m_pConnection->PutDefaultDatabase ((_bstr_t)"DB");//設置默認數據庫
m_pCommand.CreateInstance(__uuidof(Command));) V& t. T5 @% U: A) V A
m_pCommand->CommandTimeout = 5;
m_pCommand->ActiveConnection = m_pConnection;
}
}1 q2 ^7 p$ y" Q+ Y9 A. v
catch(_com_error e)///捕捉異常
{* K! ^# y4 I" f( x
CString errormessage;- V, l R/ t g! A2 @# Y
errormessage.Format("連接數據庫失敗!\r\n錯誤信息:%s",e.ErrorMessage());/ s, B! ]" ]* f; `
AfxMessageBox(errormessage);///顯示錯誤信息
}
(2)、關閉% _ R! J/ E: ~, T
//如果數據庫連接有效
if( m_pConnection->State ); V9 B1 h! R$ ^2 l: H9 X
m_pConnection->Close();
m_pConnection = NULL;
(3)、設置連接時間 //設置連接時間-----------------------------------
pConnection->put_ConnectionTimeout(long(5));9 t3 t5 n) X! e& k: Z: N
2.打開一個結果集* N' B. Y. e6 J% y! B
(1)打開,首先創建一個_RecordsetPtr實例,然后調用Open()得到一條SQL語句的執行結果
_RecordsetPtrm_pRecordset;) l; @- {5 Z5 \' g2 K. m& o1 r- Y
m_pRecordset.CreateInstance(__uuidof(Recordset)); % ~3 |" {; P/ {, K, c
// 在ADO操作中建議語句中要常用try...catch()來捕獲錯誤信息,
// 因為它有時會經常出現一些意想不到的錯誤。jingzhou xu' r; x1 n( r0 n3 H
try( c! j; L( r& ?4 G3 z6 Z
{& l* Y. w' R) a# m* h: L
m_pRecordset->Open("SELECT * FROM DemoTable",// 查詢DemoTable表中所有字段
m_pConnection.GetInterfacePtr(), // 獲取庫接庫的IDispatch指針0 t8 Q4 l' R0 V/ [0 a: ^' b" c
adOpenDynamic,8 C9 U7 k7 F& a( h/ T) u
adLockOptimistic,1 y7 [- O! \5 q! A* @
adCmdText);
}
catch(_com_error *e)8 I E$ S/ H, M" Y" s; K! F8 X
{
AfxMessageBox(e->ErrorMessage());; E# B1 o/ e) a7 P
}7 x! h0 S' j. y/ w) P
(2)關閉結果集
m_pRecordset->Close();
3.操作一個結果集
(1)、遍歷(讀取)3 Q9 \* p: I! Y: P, z# B
a)、用pRecordset->adoEOF來判斷數據庫指針是否已經移到結果集的末尾了;m_pRecordset->BOF判斷是否 在第一條記錄前面:8 L* O4 g' x3 K" x& P
while(!m_pRecordset->adoEOF)& N. _1 \1 Z/ \6 c2 M1 b
{4 O* V! Q" H2 J
var = m_pRecordset->GetCollect("Name");
if(var.vt != VT_NULL)0 @- ~3 x* y1 R( z7 z& x, ~8 [/ E
strName = (LPCSTR)_bstr_t(var);
var = m_pRecordset->GetCollect("Age");
if(var.vt != VT_NULL)
strAge = (LPCSTR)_bstr_t(var); T3 W2 r. y% U! v: v+ M& Q
m_AccessList.AddString( strName + " --> "+strAge );
m_pRecordset->MoveNext();! ^% e! I# h+ z# J7 a' ^! J/ L
}
b)、取得一個字段的值的辦法有兩種辦法, p* |; l( F8 Q v' z
一是4 [; O! k$ ?# X
//表示取得第0個字段的值 m_pRecordset->GetCollect("Name");
或者 m_pRecordset->GetCollect(_variant_t(long(0));
二是
pRecordset->get_Collect("COLUMN_NAME");9 D* l( J4 Q! h
或者 pRecordset->get_Collect(long(index));& `7 O5 G' w1 U: E0 h, s
(2)、添加+ o+ D; Q p. e
a)、調用m_pRecordset->AddNew();
b)、調用m_pRecordset->PutCollect();給每個字段賦值; T) ]+ b9 a5 z
c)、調用m_pRecordset->Update();確認
(3)、修改6 ^+ q8 U0 C% ~
(4)、刪除
a)、把記錄指針移動到要刪除的記錄上,然后調用: o1 ]9 y% \# Y/ l
Delete(adAffectCurrent) try
{
// 假設刪除第二條記錄
m_pRecordset->MoveFirst();
m_pRecordset->Move(1); # d# h/ ^; b7 v) Y4 k, B+ Q
// 從0開始
m_pRecordset->Delete(adAffectCurrent);
// 參數adAffectCurrent為刪除當前記錄
m_pRecordset->Update();
}
catch(_com_error *e)/ A# f" H& T# O7 V& Y$ y
{, T; o& p2 U. C# K& e( e% z6 U
AfxMessageBox(e->ErrorMessage());% y# Y; O. p, C! z- q
}
4.直接執行SQL語句,除了要用到結果集其余的大部分功能都可以直接用SQL語言實現5 p. g; s# P: y9 E( }
(1)、用_CommandPtr和_RecordsetPtr配合6 [& ]7 O, U; @$ Q8 [ @
_CommandPtrm_pCommand;
m_pCommand.CreateInstance(__uuidof(Command));1 x; T* A8 U) R' e2 L' j
// 將庫連接賦于它" ~; h( r, o6 i3 H. K8 {
m_pCommand->ActiveConnection = m_pConnection;
// SQL語句$ j! z& V) o+ W4 o- J5 y a
m_pCommand->CommandText = "SELECT * FROM DemoTable";
// 執行SQL語句,返回記錄集
m_pRecordset = m_pCommand->Execute(NULL, NULL,adCmdText);# {) ~8 C$ k Z+ o0 U- i( k: P
(2)、直接用_ConnectionPtr執行SQL語句+ `8 b9 I) Q* D$ O/ X
_RecordsetPtr Connection15::Execute ( _bstr_t CommandText,
VARIANT * RecordsAffected,
long Options )
其中CommandText是命令字串,通常是SQL命令。
參數RecordsAffected是操作完成后所影響的行數,
參數Options表示CommandText中內容的類型,Options可以取如下值之一:
adCmdText:表明CommandText是文本命令 * W8 I& H1 K' P2 c! [
adCmdTable:表明CommandText是一個表名
adCmdProc:表明CommandText是一個存儲過程 1 U5 k7 x2 T. t& k: o1 t
adCmdUnknown:未知4 c! J Z8 i2 U$ |/ }# }
例子:7 E- X" Q" l) u. z* O9 h2 r6 {
_variant_t RecordsAffected;
m_pConnection->Execute("UPDATE users SET old = old+1",&RecordsAffected,adCmdText); , b7 r9 h( Z: G/ `6 s3 ?) X
5.調用存儲過程
(1)、利用_CommandPtr
_CommandPtrm_pCommand;4 l9 n' O% Z, c, @; {
m_pCommand.CreateInstance(__uuidof(Command));
m_pCommand->ActiveConnection = m_pConnection; // 將庫連接賦于它0 L0 f: _2 T2 m9 R+ f) v9 Z
m_pCommand->CommandText = "Demo"; + Q5 Q7 N; u2 F% l l
m_pCommand->Execute(NULL,NULL, adCmdStoredProc);- j7 b$ A6 b* s+ u7 M; U5 S0 Y
(2)、直接用_ConnectionPtr直接調用* p- H$ l9 W0 ~2 W( G/ L
6.遍歷數據庫中的所有表名
_RecordsetPtr pSet;
HRESULT hr; . N' T& I' ?6 e, W" |8 ]( ~5 j3 I
try
{
hr = m_pConnect.CreateInstance("ADODB.Connection"); + D3 C4 L4 Q H4 Y- ?
if(SUCCEEDED(hr))
{ ' L" |" c& W$ s8 _" x
CString dd; ; z3 d- _6 C; o$ F, d* w1 `2 J
dd.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",file); # ~1 {# b+ }" S: w; q a2 f1 l
hr = m_pConnect->Open((_bstr_t)dd,"","",adModeUnknown);
pSet = m_pConnect->OpenSchema(adSchemaTables); 8 Y% ?5 ]- W0 o" S( N% O: e! M4 w; n
while(!(pSet->adoEOF))
{
//獲取表格
_bstr_t table_name = pSet->Fields->GetItem("TABLE_NAME")->Value;
//獲取表格類型 * q1 E* a# `2 x5 D
_bstr_t table_type = pSet->Fields->GetItem("TABLE_TYPE")->Value;' d- A5 N" m) @7 v9 D ~ l% U; z
//過濾一下,只輸出表格名稱,其他的省略
if ( strcmp(((LPCSTR)table_type),"TABLE")==0){3 w) ?7 ~: W1 D& |, }, }
CString tt;! ?- o+ X, j8 j8 c0 y" l
tt.Format("%s",(LPCSTR)table_name);
AfxMessageBox(tt);
} # g3 p# g: j' k7 M( ^% D
pSet->MoveNext(); ( C; s+ J& u! C3 h0 v9 S/ v
}
pSet->Close(); , W. ^% E# g, }# a1 N3 y
}
m_pConnect->Close(); ) C$ K1 t' x2 a0 |/ [; h) E
}catch(_com_error e)///捕捉異常 4 T" ^# g9 k$ s% p+ c
{
CString errormessage; b6 C7 F% Y3 C7 D" l# _) k
errormessage.Format("連接數據庫失敗!rn錯誤信息:%s",e.ErrorMessage());- S& K: D: D* \5 c: @% p
AfxMessageBox(errormessage);
return -1;2 S/ P# F, t1 T: ]: V% N& Y* h
} \+ ~) g+ a# D$ c6 D
7.遍歷一個表中的所有字段
Field * field = NULL;2 _% M' C! {) g) o. T
HRESULT hr;
Fields * fields = NULL;# O: q5 g, b/ \" x' W$ ~0 d
hr = m_pRecordset->get_Fields (&fields);//得到記錄集的字段集和
if(SUCCEEDED(hr)) 1 C/ r8 Z- V- o8 a; j
fields->get_Count(&ColCount);
//得到記錄集的字段集合中的字段的總個數
for(i=0;iItem[i]->get_Name(&bstrColName);//得到記錄集//中的字段名) i& r( x- T0 Q7 j2 q- P8 e
strColName=bstrColName;0 W* E7 L( b" O q
nameField = strColName;
m_FieldsList.AddString(nameField);
}
if(SUCCEEDED(hr))
fields->Release();//釋放指針% z: \/ V: m; S" U
附:
1、_variant_t
(1)、一般傳給這3個指針的值都不是MFC直接支持的數據類型,而要用_variant_t轉換一下9 V: x. e& U' Z( k) Y& ~6 D6 y* n
_variant_t(XX)可以把大多數類型的變量轉換成適合的類型傳入:
(2)、_variant_t var;_variant_t -> long: (long)var;
_variant_t -> CString: CString strValue = (LPCSTR)_bstr_t(var);
CString -> _variant_t: _variant_t(strSql);& G+ V1 {7 O4 M0 B
2、BSTR寬字符串與CString相互轉換" b2 i- E0 ^2 @+ S* `: B7 }1 j
BSTR bstr;- M6 Q5 q( C5 s- F1 u
CString strSql;4 T6 O; k# M1 F. g @/ e
CString -> BSTR: bstr = strSql.AllocSysString();
BSTR -> CString: strSql = (LPCSTR)bstr;" x# X2 N s1 Q1 C6 L4 U
3、_bstr_t與CString相互轉換) o( B" D0 X0 K! B8 E% l4 w8 c
_bstr_t bstr;
CString strSql;
CString -> _bstr_t: bstr = (_bstr_t)strSql;
_bstr_t -> CString: strSql = (LPCSTR)bstr;
4、關于時間
Access:表示時間的字符串#2004-4-5#; D( I/ c/ }7 m$ _
Sql:表示時間的字符串@#@#2004-4-5@#@# ^) d* B+ F) @' v) D
DateField(時間字段) select * from my_table where DateField > #2004-4-10# " g# W: M/ ~' V! T
try! ^- H# ]1 a% R6 k
{0 s4 h0 [; {$ Q" @* p! a/ t- ]
m_pCommand->CommandText = "INSERT INTO tTest(age) VALUES(@#23f2@#) ";
m_pRecordset = m_pCommand->Execute(NULL,NULL, adCmdText);
}
catch(_com_error e)///捕捉異常( _( ^2 E- n# l2 `* A4 K. N
{
CString errormessage;) F+ c! Y8 g2 [" ]9 @; J( S6 P
errormessage.Format("連接數據庫失敗!\r\n錯誤信息:%s",e.ErrorMessage());% U7 p% B: R+ }- Q |% m
AfxMessageBox(errormessage);///顯示錯誤信息: `' w# ?8 F0 n" p! T5 M
}
posted on 2011-08-09 14:21
日需博客 閱讀(339)
評論(0) 編輯 收藏 引用 所屬分類:
C C++ 、
Windows 、
技術文章 、
轉載