流量统计:
Rixu Blog (日需博客)
日需博客,每日必需来踩踩哦..
posts - 108,comments - 54,trackbacks - 0
准备:# 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
}
Logo
作者:Gezidan
出处:http://www.rixu.net    
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted on 2011-08-09 14:21 日需博客 阅读(316) 评论(0)  编辑 收藏 引用 所属分类: C C++Windows技术文章转载

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理