C++是不能的,必須使用平臺數據庫相關(guān)的動(dòng)態(tài)鏈接庫操作。使用在VC中使用ADO操作是比較簡(jiǎn)單的。
1)、引入ADO類(lèi)
#import "c:\program files\common files\system\ado\msado15.dll " \
no_namespace \
rename ( "EOF ", "adoEOF ")
(2)、初始化COM
在MFC中可以用AfxOleInit();非MFC環(huán)境中用:
CoInitialize(NULL);
CoUnInitialize();
(3)#import 包含后就可以用3個(gè)智能指針了:_ConnectionPtr、_RecordsetPtr和_CommandPtr
1.連接和關(guān)閉數據庫 (1)連接
例子:連接Access數據庫
AfxOleInit();//初始化
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance( "ADODB.Connection ");///創(chuàng )建Connection對象
if(SUCCEEDED(hr))
{
m_pConnection-> ConnectionTimeout = 0;
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));
m_pCommand-> CommandTimeout = 5;
m_pCommand-> ActiveConnection = m_pConnection;
}
}
catch(_com_error e)///捕捉異常
{
CString errormessage;
errormessage.Format( "連接數據庫失敗!\r\n錯誤信息:%s ",e.ErrorMessage());
AfxMessageBox(errormessage);///顯示錯誤信息
}
(2)、關(guān)閉
//如果數據庫連接有效
if( m_pConnection-> State )
m_pConnection-> Close();
m_pConnection = NULL;
(3)、設置連郵奔?//設置連接時(shí)間-----------------------------------
pConnection-> put_ConnectionTimeout(long(5));
2.打開(kāi)一個(gè)結果集
(1)打開(kāi),首先創(chuàng )建一個(gè)_RecordsetPtr實(shí)例,然后調用Open()得到一條SQL語(yǔ)句的執行結果
_RecordsetPtrm_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
// 在A(yíng)DO操作中建議語(yǔ)句中要常用try...catch()來(lái)捕獲錯誤信息,
// 因為它有時(shí)會(huì )經(jīng)常出現一些意想不到的錯誤。jingzhou xu
try
{
m_pRecordset-> Open( "SELECT * FROM DemoTable ",// 查詢(xún)DemoTable表中所有字段
m_pConnection.GetInterfacePtr(), // 獲取庫接庫的IDispatch指針
adOpenDynamic,
adLockOptimistic,
adCmdText);
}
catch(_com_error *e)
{
AfxMessageBox(e-> ErrorMessage());
}
(2)關(guān)閉結果集 m_pRecordset-> Close();
3.操作一個(gè)結果集
(1)、遍歷(讀取)
a)、用pRecordset-> adoEOF來(lái)判斷數據庫指針是否已經(jīng)移到結果集的末尾了;m_pRecordset-> BOF判斷是否 在第一條記錄前面: while(!m_pRecordset-> adoEOF)
{
var = m_pRecordset-> GetCollect( "Name ");
if(var.vt != VT_NULL)
strName = (LPCSTR)_bstr_t(var);
var = m_pRecordset-> GetCollect( "Age ");
if(var.vt != VT_NULL)
strAge = (LPCSTR)_bstr_t(var);
m_AccessList.AddString( strName + " --> "+strAge );
m_pRecordset-> MoveNext();
}
b)、取得一個(gè)字段的值的辦法有兩種辦法
一是
//表示取得第0個(gè)字段的值 m_pRecordset-> GetCollect( "Name ");
或者 m_pRecordset-> GetCollect(_variant_t(long(0));
二是
pRecordset-> get_Collect( "COLUMN_NAME ");
或者 pRecordset-> get_Collect(long(index));
(2)、添加
a)、調用m_pRecordset-> AddNew();
b)、調用m_pRecordset-> PutCollect();給每個(gè)字段賦值
c)、調用m_pRecordset-> Update();確認
(3)、修改
(4)、刪除
a)、把記錄指針移動(dòng)到要刪除的記錄上,然后調用Delete(adAffectCurrent) try
{
// 假設刪除第二條記錄
m_pRecordset-> MoveFirst();
m_pRecordset-> Move(1);
// 從0開(kāi)始
m_pRecordset-> Delete(adAffectCurrent);
// 參數adAffectCurrent為刪除當前記錄
m_pRecordset-> Update();
}
catch(_com_error *e)
{
AfxMessageBox(e-> ErrorMessage());
}
4.直接執行SQL語(yǔ)句,除了要用到結果集其余的大部分功能都可以直接用SQL語(yǔ)言實(shí)現
(1)、用_CommandPtr和_RecordsetPtr配合
_CommandPtrm_pCommand;
m_pCommand.CreateInstance(__uuidof(Command));
// 將庫連接賦于它
m_pCommand-> ActiveConnection = m_pConnection;
// SQL語(yǔ)句
m_pCommand-> CommandText = "SELECT * FROM DemoTable ";
// 執行SQL語(yǔ)句,返回記錄集
m_pRecordset = m_pCommand-> Execute(NULL, NULL,adCmdText);
(2)、直接用_ConnectionPtr執行SQL語(yǔ)句
_RecordsetPtr Connection15::Execute ( _bstr_t CommandText,
VARIANT * RecordsAffected,
long Options )
其中CommandText是命令字串,通常是SQL命令。
參數RecordsAffected是操作完成后所影響的行數,
參數Options表示CommandText中內容的類(lèi)型,Options可以取如下值之一:
adCmdText:表明CommandText是文本命令
adCmdTable:表明CommandText是一個(gè)表名
adCmdProc:表明CommandText是一個(gè)存儲過(guò)程
adCmdUnknown:未知
例子:
_variant_t RecordsAffected;
m_pConnection-> Execute( "UPDATE users SET old = old+1 ",&RecordsAffected,adCmdText);
5.調用存儲過(guò)程
(1)、利用_CommandPtr
_CommandPtrm_pCommand;
m_pCommand.CreateInstance(__uuidof(Command));
m_pCommand-> ActiveConnection = m_pConnection; // 將庫連接賦于它
m_pCommand-> CommandText = "Demo ";
m_pCommand-> Execute(NULL,NULL, adCmdStoredProc);
(2)、直接用_ConnectionPtr直接調用(見(jiàn)4.(2))
6.遍歷數據庫中的所有表名 _ConnectionPtr m_pConnect;
_RecordsetPtr pSet;
HRESULT hr;
try
{
hr = m_pConnect.CreateInstance( "ADODB.Connection ");
if(SUCCEEDED(hr))
{
CString dd;
dd.Format( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s ",file);
hr = m_pConnect-> Open((_bstr_t)dd, " ", " ",adModeUnknown);
pSet = m_pConnect-> OpenSchema(adSchemaTables);
while(!(pSet-> adoEOF))
{
//獲取表格
_bstr_t table_name = pSet-> Fields-> GetItem( "TABLE_NAME ")-> Value;
//獲取表格類(lèi)型
_bstr_t table_type = pSet-> Fields-> GetItem( "TABLE_TYPE ")-> Value;
//過(guò)濾一下,只輸出表格名稱(chēng),其他的省略
if ( strcmp(((LPCSTR)table_type), "TABLE ")==0){
CString tt;
tt.Format( "%s ",(LPCSTR)table_name);
AfxMessageBox(tt);
}
pSet-> MoveNext();
}
pSet-> Close();
}
m_pConnect-> Close();
}catch(_com_error e)///捕捉異常
{
CString errormessage;
errormessage.Format( "連接數據庫失敗!rn錯誤信息:%s ",e.ErrorMessage());
AfxMessageBox(errormessage);
return -1;
}
7.遍歷一個(gè)表中的所有字段
Field * field = NULL;
HRESULT hr;
Fields * fields = NULL;
hr = m_pRecordset-> get_Fields (&fields);//得到記錄集的字段集和
if(SUCCEEDED(hr))
fields-> get_Count(&ColCount);
//得到記錄集的字段集合中的字段的總個(gè)數
for(i=0;iItem[i]-> get_Name(&bstrColName);//得到記錄集//中的字段名
strColName=bstrColName;
nameField = strColName;
m_FieldsList.AddString(nameField);
}
if(SUCCEEDED(hr))
fields-> Release();//釋放指針
附:
1、_variant_t
(1)、一般傳給這3個(gè)指針的值都不是MFC直接支持的數據類(lèi)型,而要用_variant_t轉換一下
_variant_t(XX)可以把大多數類(lèi)型的變量轉換成適合的類(lèi)型傳入:
(2)、_variant_t var;_variant_t -> long: (long)var;
_variant_t -> CString: CString strValue = (LPCSTR)_bstr_t(var);
CString -> _variant_t: _variant_t(strSql);
2、BSTR寬字符串與CString相互轉換
BSTR bstr;
CString strSql;
CString -> BSTR: bstr = strSql.AllocSysString();
BSTR -> CString: strSql = (LPCSTR)bstr;
3、_bstr_t與CString相互轉換
_bstr_t bstr;
CString strSql;
CString -> _bstr_t: bstr = (_bstr_t)strSql;
_bstr_t -> CString: strSql = (LPCSTR)bstr;
4、關(guān)于時(shí)間
Access:表示時(shí)間的字符串#2004-4-5#
Sql:表示時(shí)間的字符串 ' '2004-4-5 ' '
DateField(時(shí)間字段) select * from my_table where DateField > #2004-4-10#
try
{
m_pCommand-> CommandText = "INSERT INTO tTest(age) VALUES( '23f2 ') ";
m_pRecordset = m_pCommand-> Execute(NULL,NULL, adCmdText);
}
catch(_com_error e)///捕捉異常
{
CString errormessage;
errormessage.Format( "連接數據庫失敗!\r\n錯誤信息:%s ",e.ErrorMessage());
AfxMessageBox(errormessage);///顯示錯誤信息
}
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。