Home Database Mysql Tutorial VC利用ADO组件来访问数据库的程序设计

VC利用ADO组件来访问数据库的程序设计

Jun 07, 2016 pm 03:47 PM
use data database programming components access connect

涉及到VC连接数据库,以前没有用VC去连接过数据库,便看了下源代码,稍微了解了一点,认为大致的连接方法如下: 一、ADO概述 ADO是Microsoft为最新和最强大的数据访问范例 OLE DB 而设计的,是一个便于使用的应用程序层接口。ADO 使您能够编写应用程序以通过

涉及到VC连接数据库,以前没有用VC去连接过数据库,便看了下源代码,稍微了解了一点,认为大致的连接方法如下:

一、ADO概述
  ADO是Microsoft为最新和最强大的数据访问范例 OLE DB 而设计的,是一个便于使用的应用程序层接口。ADO 使您能够编写应用程序以通过 OLE. DB 提供者访问和操作数据库服务器中的数据。ADO 最主要的优点是易于使用、速度快、内存支出少和磁盘遗迹小。ADO 在关键的应用方案中使用最少的网络流量,并且在前端和数据源之间使用最少的层数,所有这些都是为了提供轻量、高性能的接口。之所以称为 ADO,是用了一个比较熟悉的暗喻,OLE 自动化接口。

  OLE DB是一组”组件对象模型”(COM) 接口,是新的数据库低层接口,它封装了ODBC的功能,并以统一的方式访问存储在不同信息源中的数据。OLE DB是Microsoft UDA(Universal Data Access)策略的技术基础。OLE DB 为任何数据源提供了高性能的访问,这些数据源包括关系和非关系数据库、电子邮件和文件系统、文本和图形、自定义业务对象等等。也就是说,OLE DB 并不局限于 ISAM、Jet 甚至关系数据源,它能够处理任何类型的数据,而不考虑它们的格式和存储方法。在实际应用中,这种多样性意味着可以访问驻留在 Excel 电子数据表、文本文件、电子邮件/目录服务甚至邮件服务器,诸如 Microsoft Exchange 中的数据。但是,OLE DB 应用程序编程接口的目的是为各种应用程序提供最佳的功能,它并不符合简单化的要求。您需要的API 应该是一座连接应用程序和OLE DB 的桥梁,这就是 ActiveX Data Objects (ADO)。

 

二、在VC中使用ADO(开发步骤如下:)

1、引入ADO库文件

 

首先在StdAfx.h中使用#import指令引入ADO类型库,语句如下

#import "c:/Program Files/Common Files/System/ado/msado15.dll" no_namespace rename("EOF","adoEOF")

其中EOF表示文件结尾,在后面的运用中我们会用到BOF,是文件无内容可读取,即before of file

 这行语句声明在工程中使用ADO,但不使用ADO的名字空间,并且为了避免常数冲突,将常数EOF改名为adoEOF。现在不需添加另外的头文件,就可以使用ADO接口了。

 

2、初始化OLE/COM库环境
  必须注意的是,ADO库是一组COM动态库,这意味应用程序在调用ADO前,必须初始化OLE/COM库环境。在MFC应用程序里,一个比较好的方法是在应用程序主类的InitInstance成员函数里初始化OLE/COM库环境。
BOOL CMyApp::InitInstance()
{
if(!AfxOleInit())//这就是初始化COM库
{
AfxMessageBox(“OLE初始化出错!”);
return FALSE;
}

……

}

 

在CMyapp类中声明一个_ConnectionPtr myCon;      myCon用来连接数据库,在CMyapp的InitInstance()

代码:

BOOL CMYApp::InitInstance()

{

    .

    .

    .

   AfxOleInit();//ado 接口初始化
 myCon.CreateInstance(__uuidof(Connection));  //连接初始化,获取指向sql的指针

//下面也可以读取脚本文件,来获取连接数据库的另外一些信息,

}

 

然后再一些对话框对应的类中,声明一个_RecordsetPtr myRecordset;用这个myRecordset来连接表,注意每次连接完表后,open()打开,使用完后立即close()

在该对话框的OnInitDialog()函数中

OnInitDialog()

{

 myRecordset.CreateInstance(__uuidof(Recordset));   //创建一个连接实例

 

// myRecordset.CreateInstance("ADODB.Recordset")
 //在ADO操作中建议语句中要常用try...catch()来捕获错误信息,
 //因为它有时会经常出现一些意想不到的错误。

 

CCarApp * pApp= (CCarApp *) AfxGetApp();  
  myRecordset->put_CursorLocation(adUseClient);  //设置光标为客户端状态

myRecordset->Open("SELECT distinct 车辆编号  FROM 车辆信息",  pApp->myCon.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);

open()函数的参数含义依次是:SQL语句,SQL连接指针,后面三个都是定义好的常量,分别有下面的含义

//Const adOpenDynamic = 2 '动态游标功能最强,但耗资源也最多。用户对记录说做的修改,增加或删除记录都将反映到记录集中。支持全功能浏览
  //     Const adLockOptimistic = 3 '只有在调用Update方法时才锁定记录集,而在此前的其他操作仍可对当前记录进行更改、插入和删除
  //    AdCmdText 将 CommandText 作为命令或存储过程调用的文本化定义进行计算。

关于open()函数的意义,可以参看http://hi.baidu.com/ruiqing_2008/blog/item/50381334c10183bbd1a2d369.html

 

这样就可以利用游标来查询数据了, 使用CString来保存查询到的数据

CString s1;

while (!myRecordset->adoEOF)
  {
    s1=(char*)(_bstr_t)(myRecordset->Fields->GetItem(_variant_t("车辆编号"))->Value);

   //查询到数据保存在s1中,就可以对s1赋给控件变量等一系列操作
     ((CComboBox*)GetDlgItem(IDC_COMBO3))->AddString(s1);  //
    
    myRecordset->MoveNext();   //移向下一个记录

    //使用变体数据的查询方法
 //   _variant_t varNo;
 //    varNo = myRecordse->GetCollect ("车辆编号");
 //    CString strNo =(char *)_bstr_t(varNo);

  }

 //关闭表

myRecordset->Close();

 

另外,可以使用Active控件DBGrid Control来保存表中的数据,为该控件定义一个变量CDataGrid类的变量m_grid;

在对话框OnInitDialog() 里面为他绑定数据源

 m_grid.SetRefDataSource(NULL);
 m_grid.SetRefDataSource((LPUNKNOWN)myRecordset);   //实现与DBGRID控件的绑定,myRecordset在刚才已经和数据库连接起来了
 m_grid.Refresh();

}

在具体的查询过程中,我们只需要通过接口来获取数据就可以了

myRecordset->MoveFirst();    移向记录首

myRecordset->Move(-1);        移向上一条记录

myRecordset->MoveNext();    移向下一条记录

myRecordset->MoveLast();     移向记录末尾

myRecordset->AddNew();       增加一条新纪录

this->myRecordset->Delete(adAffectCurrent);   删除该条记录

在增加新纪录时候,我们可以通过获取编辑过的编辑框的内容,写入数据库

CString s1;
   GetDlgItemText(IDC_EDIT1,s1);   //获取编辑框的内容  保存到s1

写入数据集合

myRecordset->PutCollect("车辆编号",(variant_t)s1);  //向对应的列中添加数据

 

查询代码

if (myRecordset->adoEOF)    //集合尾
  { 
  return;
  }
  if (myRecordset->BOF )     //before  of  file
  {
   return;
  }

//以上表示无内容和查询

CString s1;
   s1=(char*)(_bstr_t)(myRecordset->Fields->GetItem(_variant_t("车辆编号"))->Value);

   //查询到的变体数据,强制转换保存到s1
   this->SetDlgItemText(IDC_EDIT1,s1);   //设置对应编辑框的车辆信息为刚才查询到的s1

 

 

//下面是TOTO写的ADO接口使用简介

 

3、ADO接口简介

  ADO库包含三个基本接口:_ConnectionPtr接口、_CommandPtr接口和_RecordsetPtr接口。
  _ConnectionPtr接口返回一个记录集或一个空指针。通常使用它来创建一个数据连接或执行一条不返回任何结果的SQL语句,如一个存储过程。使用_ConnectionPtr接口返回一个记录集不是一个好的使用方法。对于要返回记录的操作通常用_RecordserPtr来实现。而用_ConnectionPtr操作时要想得到记录条数得遍历所有记录,而用_RecordserPtr时不需要。

  _CommandPtr接口返回一个记录集。它提供了一种简单的方法来执行返回记录集的存储过程和SQL语句。在使用_CommandPtr接口时,你可以利用全局_ConnectionPtr接口,也可以在_CommandPtr接口里直接使用连接串。如果你只执行一次或几次数据访问操作,后者是比较好的选择。但如果你要频繁访问数据库,并要返回很多记录集,那么,你应该使用全局_ConnectionPtr接口创建一个数据连接,然后使用_CommandPtr接口执行存储过程和SQL语句。

  _RecordsetPtr是一个记录集对象。与以上两种对象相比,它对记录集提供了更多的控制功能,如记录锁定,游标控制等。同_CommandPtr接口一样,它不一定要使用一个已经创建的数据连接,可以用一个连接串代替连接指针赋给_RecordsetPtr的connection成员变量,让它自己创建数据连接。如果你要使用多个记录集,最好的方法是同Command对象一样使用已经创建了数据连接的全局_ConnectionPtr接口
,然后使用_RecordsetPtr执行存储过程和SQL语句。 

4、使用_ConnectionPtr接口
  _ConnectionPtr主要是一个连接接口,取得与数据库的连接。它的连接字符串可以是自己直接写,也可以指向一个ODBC DSN。 
_ConnectionPtr pConn;
if (FAILED(pConn.CreateInstance("ADODB.Connection")))
{
AfxMessageBox("Create Instance failed!");
return;
}


CString strSRC;
strSRC="Driver=SQL Server;Server=";
strSRC+="suppersoft";
strSRC+=";Database=";
strSRC+="mydb";
strSRC+=";UID=SA;PWD=";

CString strSQL = "Insert into student(no,name,sex,address) values(3,'aaa','male','beijing')";

_variant_t varSRC(strSRC);
_variant_t varSQL(strSQL);
_bstr_t bstrSRC(strSRC);

if (FAILED(pConn->Open(bstrSRC,"","",-1)))
{
AfxMessageBox("Can not open Database!");
pConn.Release();
return;
}

COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);

pConn->Execute(_bstr_t(strSQL),&vtOptional,-1);

pConn.Release();

AfxMessageBox("ok!");


5、使用_RecordsetPtr接口(以连接SQL Server为例)
_RecordsetPtr pPtr;
if (FAILED(pPtr.CreateInstance("ADODB.Recordset")))
{
AfxMessageBox("Create Instance failed!");
return FALSE;
}

CString strSRC;
strSRC="Driver=SQL Server;Server=";
strSRC+="210.46.141.145";
strSRC+=";Database=";
strSRC+="mydb";
strSRC+=";UID=sa;PWD=";
strSRC+="sa";

CString strSQL = "select id,name,gender,address from personal";

_variant_t varSRC(strSRC);
_variant_t varSQL(strSQL);

if(FAILED(pPtr->Open(varSQL,varSRC,adOpenStatic,adLockOptimistic,adCmdText)))
{
AfxMessageBox("Open table failed!");
pPtr.Release();
return FALSE;
}

while(!pPtr->GetadoEOF())
{
_variant_t varNo;
_variant_t varName;
_variant_t varSex;
_variant_t varAddress;

varNo = pPtr->GetCollect ("id");
varName = pPtr->GetCollect ("name");
varSex = pPtr->GetCollect ("gender");
varAddress = pPtr->GetCollect ("address");

CString strNo =(char *)_bstr_t(varNo);
CString strName =(char *)_bstr_t(varName);
CString strSex =(char *)_bstr_t(varSex);
CString strAddress =(char *)_bstr_t(varAddress);

strNo.TrimRight();
strName.TrimRight();
strSex.TrimRight();
strAddress.TrimRight();

int nCount = m_list.GetItemCount();
int nItem = m_list.InsertItem (nCount,_T(""));
m_list.SetItemText (nItem,0,strNo);
m_list.SetItemText (nItem,1,strName);
m_list.SetItemText (nItem,2,strSex);
m_list.SetItemText (nItem,3,strAddress);

pPtr->MoveNext();
}

pPtr->Close();
pPtr.Release();


6、使用_CommandPtr接口
  _CommandPtr接口返回一个Recordset对象,并且提供了更多的记录集控制功能,以下代码示例了使用_CommandPtr接口的方法:

  代码:使用_CommandPtr接口获取数据
_CommandPtr pCommand;
_RecordsetPtr pRs;
pCommand.CreateInstance(__uuidof(Command));
pCommand->ActiveConnection=pConn;
pCommand->CommandText="select * from student";
pCommand->CommandType=adCmdText;
pCommand->Parameters->Refresh();
pRs=pCommand->Execute(NULL,NULL,adCmdUnknown);
_variant_t varValue = pRs->GetCollect("name");
Cstring strValue=(char*)_bstr_t(varValue);


7、关于数据类型转换由于COM对象是跨平台的,它使用了一种通用的方法来处理各种类型的数据,因此Cstring 类和COM对象是不兼容的,我们需要一组API来转换COM对象和C++类型的数据。_vatiant_t和_bstr_t就是这样两种对象。它们提供了通用的方法转换COM对象和C++类型的数据。 

 

 

源代码是最好的老师

数据库服务器一直没有配置好,所以没有跟踪测试下,过两天配好数据库试试

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

Single card running Llama 70B is faster than dual card, Microsoft forced FP6 into A100 | Open source Single card running Llama 70B is faster than dual card, Microsoft forced FP6 into A100 | Open source Apr 29, 2024 pm 04:55 PM

FP8 and lower floating point quantification precision are no longer the "patent" of H100! Lao Huang wanted everyone to use INT8/INT4, and the Microsoft DeepSpeed ​​team started running FP6 on A100 without official support from NVIDIA. Test results show that the new method TC-FPx's FP6 quantization on A100 is close to or occasionally faster than INT4, and has higher accuracy than the latter. On top of this, there is also end-to-end large model support, which has been open sourced and integrated into deep learning inference frameworks such as DeepSpeed. This result also has an immediate effect on accelerating large models - under this framework, using a single card to run Llama, the throughput is 2.65 times higher than that of dual cards. one

AI startups collectively switched jobs to OpenAI, and the security team regrouped after Ilya left! AI startups collectively switched jobs to OpenAI, and the security team regrouped after Ilya left! Jun 08, 2024 pm 01:00 PM

Last week, amid the internal wave of resignations and external criticism, OpenAI was plagued by internal and external troubles: - The infringement of the widow sister sparked global heated discussions - Employees signing "overlord clauses" were exposed one after another - Netizens listed Ultraman's "seven deadly sins" Rumors refuting: According to leaked information and documents obtained by Vox, OpenAI’s senior leadership, including Altman, was well aware of these equity recovery provisions and signed off on them. In addition, there is a serious and urgent issue facing OpenAI - AI safety. The recent departures of five security-related employees, including two of its most prominent employees, and the dissolution of the "Super Alignment" team have once again put OpenAI's security issues in the spotlight. Fortune magazine reported that OpenA

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

See all articles