VC use ADO to develop database application program Concise tutorial _c language

Source: Internet
Author: User
Tags dsn odbc object model ole

This article describes the VC in the use of ADO to develop database application methods. Share to everyone for your reference, specific as follows:

An overview of ADO

ADO is designed by Microsoft for the latest and most powerful data access paradigm OLE DB, and is an Easy-to-use application-layer interface. ADO enables you to write applications to pass OLE. DB providers access and manipulate data in the database server. The main advantages of ADO are ease of use, speed, low memory costs, and small disk remains. ADO uses the least amount of network traffic in critical applications and uses a minimal number of layers between the front-end and data sources, all to provide lightweight, high-performance interfaces. Called ADO, it uses a more familiar metaphor, OLE Automation interface.

OLE DB is a set of Component Object Model (COM) interfaces, a new low-level interface to the database that encapsulates the capabilities of ODBC and accesses data stored in different sources of information in a uniform manner. OLE DB is the technical basis for Microsoft UDA (Universal Data Access) policy. OLE DB provides high-performance access to any data source, including relational and non relational databases, e-mail and file systems, text and graphics, custom business objects, and so on. That is, OLE DB is not limited to ISAM, Jet, or even relational data sources, it can handle any type of data, regardless of their format and storage methods. In practical applications, this diversity means access to data residing in Excel spreadsheets, text files, e-mail/directory services, and even mail servers, such as Microsoft Exchange. However, the purpose of the OLE DB application programming interface is to provide the best functionality for a variety of applications, and it does not conform to the simplistic requirements. The API you need should be a bridge between the application and OLE DB, which is ActiveX Data Objects (ADO).

Second, the use of ADO in VC

1, the introduction of the ADO library files

Before using ADO, we must introduce the #import into the ADO library file in the engineering stdafx.h file, so that the compiler can compile correctly. The code looks like this:

Code 1: Introducing an ADO library file with #import

#import "C:\Program Files\Common Files\system\ado\msado15.dll"
no_namespaces rename ("EOF" adoeof)

This line statement declares that ADO is used in the project, but does not use the namespace of ADO and, in order to avoid constant collisions, rename the constant EOF to adoeof. Now you can use the ADO interface without adding another header file.

2. Initialize the Ole/com library environment

It is important to note that the ADO library is a set of COM dynamic libraries, which means that the application must initialize the Ole/com Library environment before invoking ADO. In an MFC application, a better approach is to initialize the Ole/com library environment in the InitInstance member function of the application's main class.

Code 2: Initializing the ole/com library environment

BOOL cadoapp::initinstance ()
{
if (! AfxOleInit ())
{
AfxMessageBox ("OLE initialization error!");
return FALSE;
}
...
}

function AfxOleInit initializes the Ole/com library environment each time the application starts.

Like DAO and CDatabase, ADO is made up of several interfaces:

_connectionptr,_commandptr and _RecordsetPtr.

Unlike DAO and CDatabase, ADO is based on COM interfaces, so if you're not in touch with COM, you should find the books and learn about COM before using ADO.

3, ADO Interface Introduction

The ADO library contains three basic interfaces: The _connectionptr interface, the _commandptr interface, and the _RecordsetPtr interface.

The _connectionptr interface returns a recordset or a null pointer. It is typically used to create a data connection or to execute a SQL statement that does not return any results, such as a stored procedure. Returning a recordset using the _connectionptr interface is not a good way to use it. Typically, like CDatabase, you use it to create a data connection, and then use other objects to perform data input and output operations.

The _commandptr interface returns a recordset. It provides an easy way to execute stored procedures and SQL statements that return a recordset. When using the _commandptr interface, you can use the global _connectionptr interface, or you can use the connection string directly in the _commandptr interface. If you perform only one or several data access operations, the latter is a better choice. But if you want to access the database frequently and return a lot of recordsets, you should use the global _connectionptr interface to create a data connection and then use the _commandptr interface to execute stored procedures and SQL statements.

_RecordsetPtr is a Recordset object. Compared with the above two kinds of objects, it provides more control functions to the recordset, such as record lock, cursor control and so on. Like the _commandptr interface, it does not necessarily use a data connection that has already been created, you can use a connection string instead of the connection pointer to assign the _RECORDSETPTR's connection member variable to create the data connection itself. If you want to use multiple recordsets, the best approach is to use the same global _connectionptr interface as the command object that has already created the data connection, and then execute the stored procedures and SQL statements using _RECORDSETPTR.

4, the use of _connectionptr interface

_CONNECTIONPTR is a connection interface that resembles CDatabase and CDaoDatabase. They work in a similar principle. First create a _CONNECTIONPTR interface instance, and then point to and open an ODBC data source or OLE DB data provider (Provider). The following code and CDaoDatabase create a separate data connection based on DSN and non-DSN.

Code 3: Using CDaoDatabase (DSN based)

CDaoDatabase MyDb = new CDaoDatabase ();
Mydb.open (Null,false,false, "odbc;dsn=samp; Uid=admin; Pwd=admin ");

Code 4: Using CDaoDatabase (non-DSN based)

CDaoDatabase MyDb = new CDaoDatabase ();
Mydb.open (Null,false,false, "Odbc;driver={sql Server}"; Server=server;
Database=samp; Uid=admin; Pwd=admin ");

Code 5: Using _connectionptr (DSN based)

_connectionptr MyDb;
Mydb.createinstance (__uuidof (Connection));
Mydb->open ("Dsn=samp; Uid=admin; Pwd=admin "," "," ",-1);

Code 6: Using _connectionptr (non-DSN based)

_connectionptr MyDb;
Mydb.createinstance (__uuidof (Connection));
Mydb->open ("PROVIDER=SQLOLEDB; Server=server;database=samp; Uid=admin;
Pwd=admin "," "," ",-1);

5, the use of _RecordsetPtr interface

The use of the _RecordsetPtr interface is similar to the CDaoDatabase, and you will find that using the _RecordsetPtr interface is very simple (the following code uses the data connection already created above) by comparing the following code:

Code 7: Execute the SQL statement using CDaoDatabase

CDaoRecordset MySet = new CDaoRecordset (MyDb);
Myset->open (Afx_dao_use_default_type, "select * from T_samp");

Now using ADO:

Code 8: Execute the SQL statement using _RecordsetPtr

_RecordsetPtr MySet;
Myset.createinstance (__uuidof (Recordset));
Myset->open ("SELECT * from Some_table",
mydb.getinterfaceptr (), adopendynamic,adlockoptimistic,adcmdtext);

Now that we have a data connection and a recordset, we can then use the data. As you can see from the following code, using the _RecordsetPtr interface of ADO, you don't need to use a large and complex data structure variant as frequently as DAO, and it's one of the advantages of ADO to cast a variety of datatype. Assuming that the program has a ListBox control called M_list, the following code we use the _RecordsetPtr interface to get the recordset data and populate the ListBox control:

Code 9: Using DAO to access data

VARIANT * Vfieldvalue;
COleVariant covfieldvalue;
CString Holder;
while (! Myset->iseof ())
{
myset->getfieldvalue ("Field_1", covfieldvalue);
Vfieldvalue = (lpvariant) covfieldvalue;
if (vfieldvalue->vt!-vt_null)
{
Holder.format ("%s", vfieldvalue->pbval);
M_list.addstring (Holder);
}
Myset.movenext ();
}

Code 10: Accessing Data Using ADO

_variant_t Holder
try{while
(! myset->adoeof)
{
Holder = Myset->getcollect ("Field_1");
if (holder.vt!=vt_null)
m_list.addstring ((char*) _bstr_t (Holder));
Myset->movenext ();
}
catch (_com_error * e)
{
CString error = E->errormessage ();
AfxMessageBox (E->errormessage ());
}
catch (...)
{
MessageBox ("ADO has an error!");
}

You must always catch ADO errors in your code with try and catch, otherwise ADO errors can crash your application. When ADO has a run-time error, such as when the database does not exist, the OLE DB data provider automatically creates a _com_error object and populates the error information with the member variables for that object.

6, the use of _commandptr interface

The _commandptr interface returns a Recordset object and provides more recordset control features, and the following code example uses the _commandptr interface:

Code 11: Using the _commandptr interface to get the data

_commandptr Pcommand;
_RecordsetPtr MySet;
Pcommand.createinstance (__uuidof (Command));
pcommand->activeconnection=mydb;
pcommand->commandtext= "SELECT * from some_table";
pcommand->commandtype=adcmdtext;
Pcommand->parameters->refresh ();
Myset=pcommand->execute (Null,null,adcmdunknown);
_variant_t thevalue = Myset->getcollect ("Field_1");
CString svalue= (char*) _bstr_t (thevalue);

7. About data type conversions

Since COM objects are cross-platform and use a common approach to handling various types of data, the CString class and COM objects are incompatible and we need a set of APIs to convert COM objects and C + + type data. _vatiant_t and _bstr_t are two kinds of objects. They provide a common way to convert COM objects and C + + types of data.

8. Summary

The trend of data access development is OLE DB. The simplest way to use OLE DB is to ado.ado the object hierarchy model encapsulates the database access details, providing a very good data access strategy for C + + programmers.

I hope this article will help you with VC + + program design.

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.