VC++用ADO連接Oracle數據庫

編程思路:



一、創建對話框應用程序


二、編輯對話框資源

控件ID及標題

連接Access數據庫

IDC_QUERY                               查詢


三、添加變量、函數

       1、添加變量

// DBQuery.h : main header file for the DBQUERY application
public:
......
_ConnectionPtr m_pConnection;

// DBQueryDlg.h : header file

public:
_RecordsetPtr m_pRecordset; 
CListCtrl m_ListCtrl;


       2、添加函數

              a、添加消息響應函數

              b、添加函數


四、添加代碼

         1、添加輸入語句

// stdafx.h : include file for standard system include files,

......

#import "C:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename("EOF", "adoEOF")

         2、於“Resource.h”文件內添加資源“IDC_LIST_DB ”

#define IDC_QUERY                       1000
#define IDC_LIST_DB                     1001


         3、 於“”文件內添加外部變量

// DBQueryDlg.h : header file
......
extern CDBQueryApp theApp;
class CDBQueryDlg : public CDialog

         4、添加函數代碼

               a、於“DBQueryDlg.cpp”文件內添加函數代碼

BOOL CDBQueryDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
   CString strAboutMenu;
   strAboutMenu.LoadString(IDS_ABOUTBOX);
   if (!strAboutMenu.IsEmpty())
   {
    pSysMenu->AppendMenu(MF_SEPARATOR);
    pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
   }
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE);    // Set big icon
SetIcon(m_hIcon, FALSE);   // Set small icon
// TODO: Add extra initialization here
CRect rect;
GetClientRect(&rect);
CRect rectQuery;
GetDlgItem(IDC_QUERY)->GetWindowRect(&rectQuery);
ScreenToClient(&rectQuery);
rect.left+=10;
rect.top+=10;
rect.right-=10;
rect.bottom=rectQuery.top-10;
BOOL bl=m_ListCtrl.Create(WS_BORDER|WS_VISIBLE|LVS_REPORT,rect,this,IDC_LIST_DB);
m_ListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);
m_ListCtrl.InsertColumn(0,"學號",LVCFMT_LEFT,50); 
m_ListCtrl.InsertColumn(1,"姓名",LVCFMT_LEFT,50);
int n=m_ListCtrl.InsertItem(0,"1");
m_ListCtrl.SetItemText(n,1,"張三");
n=m_ListCtrl.InsertItem(1,"2");
m_ListCtrl.SetItemText(n,1,"李四"); 
return TRUE; // return TRUE unless you set the focus to a control 
}

void CDBQueryDlg::OnQuery() 
{
// TODO: Add your control notification handler code here
CString strSQL="";
int nFieldsCount=0;
long i=0;
CString strFieldName="";
m_pRecordset.CreateInstance("ADODB.Recordset");//創建Recordset實例
strSQL="SELECT TNO,TN,SEX,AGE,PROF,DEPT FROM T WHERE AGE>30";
try
{
   m_pRecordset->Open((_variant_t)strSQL,(IDispatch*)theApp.m_pConnection,
    adOpenDynamic,adLockOptimistic,adCmdText);//打開記錄集 
}
catch (_com_error* e)
{
   AfxMessageBox(e->ErrorMessage());//彈出錯誤對話框
}

try
{
   nFieldsCount=m_pRecordset->GetFields()->Count;//得到字段數
}
catch (_com_error* e)
{
   AfxMessageBox(e->ErrorMessage());//彈出錯誤對話框
}

//清空列表控件
int nListColCount=0;
nListColCount=m_ListCtrl.GetHeaderCtrl()->GetItemCount();
m_ListCtrl.DeleteAllItems();
for (i=nListColCount-1;i>=0;i--)
{
   m_ListCtrl.DeleteColumn(i);
}

//添加新的字段,字段名爲讀取表中的各字段名
for (i=0;i<nFieldsCount;i++)
{
   strFieldName=LPCTSTR(m_pRecordset->GetFields()->GetItem(_variant_t(i))->Name);
   m_ListCtrl.InsertColumn(i,strFieldName,LVCFMT_LEFT,50,50);
}

_variant_t var;
CString strItemValue;//當前記錄當前字段的值
int nItem=0;//當前插入記錄的行數
long nFirstCol=0;//第一列的索引,爲0
int nIndex=0;//標記當前記錄索引,從0開始

while (!m_pRecordset->adoEOF)
{
   //得到當前記錄第一個字段的值
   var=m_pRecordset->GetCollect(_variant_t(nFirstCol));
   if (var.vt!=VT_NULL)
   {
    //類型轉換,將_variant_t轉換爲CString
    strItemValue=LPCTSTR(_bstr_t(var));
   }
   //插入記錄並填入第一個字段的值
   nItem=m_ListCtrl.InsertItem(nIndex,strItemValue);
   //循環一下,讀取數據庫中當前記錄的值並填入列表控件
   for (i=1;i<nFieldsCount;i++)
   {
    var=m_pRecordset->GetCollect(_variant_t(i));
    if (var.vt!=VT_NULL)
    {
     strItemValue=LPCTSTR(_bstr_t(var));
     m_ListCtrl.SetItemText(nItem,i,strItemValue);
    }
   }
   m_pRecordset->MoveNext();//轉入數據庫下一記錄
   nIndex++;//當前記錄索引加1
}

//防止閃爍
m_ListCtrl.ShowWindow(SW_HIDE);
for (i=0;i<nFieldsCount;i++)
{
   //自動調整列寬
   m_ListCtrl.SetColumnWidth(i,LVSCW_AUTOSIZE_USEHEADER);
}
m_ListCtrl.ShowWindow(SW_SHOW);  
}

                 b、於“DBQuery.cpp”文件添加函數代碼

BOOL CDBQueryApp::InitInstance()
{
AfxEnableControlContainer();
AfxOleInit();///初始化COM庫
HRESULT hr;
hr=m_pConnection.CreateInstance("ADODB.Connection");
if (FAILED(hr))   return FALSE;
try
{
   hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=School.mdb","","",adModeUnknown);
}
catch (_com_error &e)
{
   CString errormessage;
   errormessage.Format("連接數據庫失敗!\r\n錯誤信息:%s",e.ErrorMessage());
   AfxMessageBox(errormessage);///顯示錯誤信息
   return FALSE;  
}
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls();    // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CDBQueryDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
   // TODO: Place code here to handle when the dialog is
   // dismissed with OK
}
else if (nResponse == IDCANCEL)
{
   // TODO: Place code here to handle when the dialog is
   // dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}

int CDBQueryApp::ExitInstance() 
{
// TODO: Add your specialized code here and/or call the base class
if(m_pConnection->State)
   m_pConnection->Close(); 
return CWinApp::ExitInstance();
}

五、編譯

六、運行

         將數據庫文件與該程序置於同一文件夾打開。

七、函數說明

        1、AfxOleInit函數聲明

         BOOL AFXAPI AfxOleInit()

         功能:初始化COM庫。成功則返回非零值;否則返回零。

        2、_ConnectiongPtr->Open函數聲明

         HRESULT Connectiong15::Open(_bstr ConnectiongString,_bstr_t UserID,_bstr_t Password,long Optiongs)

        ConnectiongString:連接字符串。

        UserID:用戶名。

        Password:登錄密碼。

         Optiongs:連接選項,用於指定Connectiong對象對數據更新的許可權。

          Optiongs可以是:

           adModeunknown;默認,沒設置當前許可權

          adModeRead:只讀。

          adModeWrite:只寫。

          adModeReadWrite:可讀寫。

          adModeShareDenyRead:阻止其他connectiong對象以讀權限打開連接。

          adModeShareDenyWrite:阻止其他connectiong對象以寫權限打開連接。

          adModeShareExclusive:阻止其他connectiong對象打開連接。

          adModeShareDenyNone:允許其他程序或對象以任何權限建立連接功能,設置靜態控件功能。

          功能:建立於數據庫服務器的連接。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章