Visual c ++ program encapsulation ADO class

Source: Internet
Author: User

1 Introduction

In the past few years, Microsoft has successively introduced several data access technologies, namely Dao (data access objects) and rdo (Remote Data Objects ), now it is ADO (acticex data objects ). ADO is a new interface for Microsoft database application development and is Microsoft's latest data access technology. It is designed to work with the new data access layer ole db provider to provide universal data access ). ADO provides us with a familiar and high-level automation encapsulation interface for ole db, which simplifies the data access process and increases the flexibility of data access, is the mainstream technology of the current data access interface.

It is very convenient to use VB or VBScript to operate ADO. However, if C ++ or Java is used, data structures like variants must be processed, therefore, it is a headache for C ++ developers to convert the data structure with C ++. Moreover, ADO is a programming interface at the application layer. It accesses data through the COM interface provided by ole db. to access the database using ADO, Many API functions and ADO objects are required. For Beginners, it may be difficult. Even if you are a programmer of ADO, you will get bored by writing a large number of redundant code of the same ADO. I have read many articles on the Internet that encapsulate ado, but they also have their own advantages and disadvantages. In Visual C ++, the author tries to encapsulate ADO Access database classes to make it easier to use the existing VC data types, simplify the logic of application writing, and increase the readability of the program. This article provides the encapsulation method and source program used by the author.

2. Create an ADO encapsulation class

2.1 basic ADO object model

The ADO model contains connection objects, command objects, domain objects, parameter objects, record set objects, and error objects. There is a hierarchical relationship between objects, as shown in relationship 1.

The basic process of using ADO to access the database in VC is:

Initialize the com library and introduce the ADO Library File

Connect to a database using a connection object

Use the established connection and obtain the result record set by using the recordset object for query and processing.

Close the connection to release the object after use

2.2 basic operation functions and data structures

The encapsulated ADO class should include the following functions and data structures:

1) Establish Database Connection function opendatabase ()

The connection object is used to connect to a database through ADO. It is a physical connection to the database and manages the communication between applications and databases. For most database systems, each physical connection consumes a large amount of system memory, which is a valuable system resource and cannot be abused. Considering the application efficiency, each database client only uses one physical connection, and the application should be released after it is completed.

2) Close the database connection function closedatabase ()

3) SQL query statement function select ()

The establishment of record sets and the acquisition of query results are key issues that affect the efficiency of applications. Because the results of each query may be different, each query statement must create a record set object.

4) execute the SQL statement function excute () without returning results ()

5) query result array pdata

For the convenience of data type conversion, we convert the data types in the record set to the cstring type and store them in the query result array pdata, because c ++'s cstring is an efficient and powerful class, we can easily read the query results in the record set.

6) Result array size: nresultrow and nresultcol
2.3 ADO encapsulation Class header file
The encapsulation Class header file ADODB. H is defined as follows:

Class cadodb: Public cobject
{
Public:
Cadodb (); // Constructor
~ Cadodb (); // destructor
Public:
Int nresultrow; // number of rows in the query result
Int nresultcol; // Number of query result Columns
Cstringarray pdata; // the size of the query result array is nrow * ncol.
Cstring errormessage; // ADO error message
Bool opendatabase (cstring dsnname, cstring suserid, cstring spassword );
// Open the database connection and enter the DSN name, user ID, and password.
Int select (cstring SQL); // execute the SQL query statement and put the result in the array pdata.
Int excute (cstring SQL); // No worthwhile SQL statement is returned for execution
Bool closedatabase (); // closes the database connection
Protected:
_ Connectionptr m_pconnection; // defines the connection pointer.
};

2.4 encapsulation class implementation file
The encapsulation class implementation file ADODB. cpp is as follows:

# Include "stdafx. H"
# Include "ADODB. H"
Cadodb: cadodb () // constructor to complete Initialization
{
Nresultrow = 0 ;//
Nresultcol = 0; // Number of Record Sets and number of Columns
M_pconnection = NULL;
}
Cadodb ::~ Cadodb () // closes the physical connection of the database
{
If (m_pconnection) m_pconnection-> close ();
M_pconnection = NULL;
}
Bool cadodb: opendatabase (cstring dsnname, cstring suserid, cstring spassword)
{// Open the database connection
...
Hresult hR = m_pconnection.createinstance ("ADODB. Connection"); // create a connection object
HR = m_pconnection-> open (_ bstr_t) dsnname, (_ bstr_t) suserid, (_ bstr_t) spassword, adopenunspecified); // connect to the database
...
}
Int cadodb: Select (cstring sqlstr) // SQL query statement Function
{...
Try
{
HR = m_precordset.createinstance ("ADODB. recordset"); // create a record set object instance
HR = m_precordset-> putref_activeconnection (m_pconnection); // set the connection object
HR = m_precordset-> open (vsqlstring, vnull, adopendynamic, adlockoptimistic, ad1_text); // open the record set
Nresultcol = m_precordset-> fields-> getcount (); // gets the total number of columns in the record set.
While (! M_precordset-> adoeof)
{
For (j = 0; j <nresultcol; j ++) // retrieve a column of data
{
Vvalue = m_precordset-> fields-> item [(long) J]-> value; // retrieves field data of the current record
If (vvalue. VT! = 1) // The data is not empty
{
Int type = vvalue. vt;
If (variantchangetype (& vvalue1, & vvalue, 0, vt_bstr) = s_ OK) // convert the data type (as a string)
STR = vvalue1.bstrval; // Save the result value to the Temporary Variable Str.
}
If (pdata. getsize () <I * nresultcol + J + 1) // dynamically set the array size
M_presult.setsize (I * nresultcol + J + 1 );
Pdata [I * nresultcol + J] = STR; // Save the result to the array.
M_precordset-> movenext (); // move the record set pointer to the next row
I ++;
}
M_precordset-> close ();
M_precordset = NULL;
Nresultrow = I;
}
Catch (_ com_error e) // catch an exception
{
...
}
Pdata-> freeextra (); // Release excess memory space
Return nresultrow;
}
...

3. Use ADO Encapsulation

After the ADO encapsulation class is set up, it is very easy to use the database. The CPP file to be queried by the database contains the ADO encapsulation Class header file "ADODB. H", and then defines a cadodb class pointer. The next step is to open the database connection. Use the encapsulated class member function opendatabase (...), Enter the DSN name, user name, and password of the database to connect. Note that if you connect to multiple databases at the same time, you must declare multiple cadodb object pointers to ensure that the database connection object is global and unique. Next, call the member function select to obtain the database query result. After execution, the query result is placed in the member character array pointer pdata of cadodb. The array size can be obtained from the member variables nresultrow and nresultcol. The basic steps are as follows:

Add the Import Statement of the ADO library to "stdafx. H"

# Import "C: Program filescommon filessystemadomsado15.dll" no_namespace Rename ("EOF", "adoeof ")

Initialize the COM object in the application class and add the following statement to initinstance ():

Afxoleinit ();

Add the Declaration file of the encapsulation class

# Include "ADODB. H"
...

Define encapsulation objects

Cadodb ado1; // connect to database 1
Cadodb ado2; // connect to database 2
...
Ado1.opendatabase ("Data Source Name", "User ID", "User Password") // creates a connection and calls
Ado1.select ("select * from table name"); // execute an SQL query statement
Int nrow = ado1.getresultrow (); // gets the number of records
Int ncol = ado1.getresultcol (); // gets the number of record Columns
For (I = 0; I <nrow; I ++) // obtain the query result
For (j = 0; j <ncol; j ++)
Printf ("the value of column % d in row % d is % s", I, j, ado1.pdata [I * ncol + J];
...
Ado1.closedatabase (); // close the database connection after use

4. Conclusions and suggestions

After the ADO class is encapsulated, the process of operating the database in the application becomes simple. For general database applications, and when the data volume is not large, this encapsulation class has been able to cope with, and is also satisfied with the use efficiency. However, this encapsulation does not take into account the optimization of data access. The database uses a dynamic connection mode, and the record set is not processed by page. The ADO buffer size and cursor type both use the default settings, these may reduce the performance of encapsulation classes in actual use. You can modify them based on different application situations.


 

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.