Operating an Access database directly through ADO

Source: Internet
Author: User
Tags odbc object model ole table name wrapper access database create database

I am in the "directly through the ODBC read, write Excel form file" and "directly through the DAO read, write Access file", has introduced the ODBC and DAO two kinds of database access technology Basic use method, this time to give you the ADO database access technology use method. ADO (Active Data Object) is actually an automated interface (IDispatch) technology based on the COM (Component Object model), and is based on OLE DB (object-connected and embedded databases), after OLE DB's carefully packaged database access technology, which allows you to quickly create database applications. ADO provides a very simple set of objects that encapsulate generally common data access details. Because ODBC data sources also provide a general OLE DB Privider, ADO can apply not only its own OLE DB Privider, but all ODBC drivers as well. For additional details about OLE DB and ADO, readers can check out the relevant books or MSDN on their own, which is not explained here. Let's go straight to the topic: How to Master ADO Database access technology. The operation of ADO and the DAO in front of the operation in many ways there are similarities, here, the author in order to more effectively explain its use, using VC6.0 to do a sample program--adorwaccess, this example program can directly through ADO to operate an Access database, The example program works as shown in the following illustration:

In the sample program we still use the original library structure, the database name Demo.mdb, the table name in the library demotable, the table field name (name) and the age of two fields, to construct the Access database required by the sample program operation. This is also compatible with the library structure in the example source code of the previous two articles.

Let's take a look at the basic steps and methods of using ADO database access technology:

First, use the #import statement to refer to the Component type library (*.TLB) that supports ADO, where the type library can be positioned as part of an executable program (DLL, EXE, and so on) in its own program's subsidiary resources. Such as: is positioned in the msado15.dll of the satellite resources, only need to directly use the #import reference it can. You can add the following statement directly to the Stdafx.h file to implement:

#import "c:\program files\common files\system\ado\msado15.dll" \
  no_namespace \
  rename ("EOF", "adoEOF") 

Where the pathname can be set from the line according to the path of the ADO support file installed on your system. When the compiler encounters a #import statement, it generates a wrapper class for the interface in the Reference component type library, #import语句实际上相当于执行了API涵数LoadTypeLib (). #import语句会在工程可执行程序输出目录中产生两个文件, respectively, *.TLH (type library header file) and *.tli (type library implementation file), which generate smart pointers for each interface, and declare for various interface methods, enumeration types, CLSID, etc. Create a series of packaging methods. Statement no_namespace that the ADO object does not use namespaces, rename ("EOF", "adoeof") explains that the end flag EOF in ADO is changed to adoeof to avoid conflicts with naming in other libraries.

Secondly, the initialization of the component in the initial process of the program, generally can be used CoInitialize (NULL) to implement, this method at the end to turn off the initialization of COM, you can use the following statement CoUninitialize (), to implement. In MFC, you can also use an alternative method to initialize COM, which requires only one statement to automate the initialization of COM and the end of COM operations for us, as shown in the following statement: AfxOleInit ();

Then, you can use the operation of ADO directly. We often use only the preceding reference to the type library with the #import statement, the generated wrapper class. The three of the smart pointers declared in TLH, respectively, are _connectionptr, _RecordsetPtr, and _commandptr. The following are an introduction to how they are used:

1. _connectionptr smart pointers, typically used to open, close a library connection, or use its Execute method to execute a command statement that does not return a result (similar to the Execute method in _commandptr).

--Open a library connection. Create an instance pointer and open a library connection with open, which returns a IUnknown Automation interface pointer. The code looks like this:

_ConnectionPtr  m_pConnection;
// 初始化COM,创建ADO连接等操作
AfxOleInit();
m_pConnection.CreateInstance(__uuidof(Connection));
// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息,
// 因为它有时会经常出现一些意想不到的错误。jingzhou xu
try        
{  
  // 打开本地Access库Demo.mdb
  m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Demo.mdb","","",adModeUnknown);
}
catch(_com_error e)
{
  AfxMessageBox("数据库连接失败,确认数据库Demo.mdb是否在当前路径下!");
  return FALSE;
}

--Closes a library connection. If the connection state is valid, the Close method closes it and assigns it a null value. The code looks like this:

if(m_pConnection->State)
    m_pConnection->Close();
m_pConnection= NULL;

2, _RecordsetPtr intelligent pointer, can be used to open the database table, and can be in the table records, fields and so on a variety of operations.

--Open the data table. Open the datasheet with the table named Demotable in the library, with the following code:

_RecordsetPtr  m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息,
// 因为它有时会经常出现一些意想不到的错误。jingzhou xu
try
{
  m_pRecordset->Open("SELECT * FROM DemoTable",        // 查询DemoTable表中所有字段
            theApp.m_pConnection.GetInterfacePtr(),   // 获取库接库的IDispatch指针
            adOpenDynamic,
            adLockOptimistic,
            adCmdText);
}
catch(_com_error *e)
{
  AfxMessageBox(e->ErrorMessage());
} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.