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:允许其他程序或对象以任何权限建立连接功能,设置静态控件功能。

          功能:建立于数据库服务器的连接。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值