Tutorials to .com

Tutorials to .com » Software » C » Using Visual C + + development database application (f)

Using Visual C + + development database application (f)

Print View , by: iSee ,Total views: 11 ,Word Count: 5208 ,Date: Sat, 18 Apr 2009 Time: 5:11 AM

Using Visual c + + development database application (f)

5 using the OLE DB

5.1 Overview

OLE DB provides users with the existence of a unified approach to access to all different types of data sources. OLE DB can be in different data source to convert. The use of OLE DB, the development of client-side data access when carrying out only very little focus on some of the details without having to understand a large number of different database access protocol.

OLE DB is a set of COM interfaces to access the data through the ActiveX interface. The OLE DB interface quite common enough to provide a unified means of access to data, regardless of the data storage method used. At the same time, OLE DB will also allow developers to continue to use the basis of the advantages of database technology without having to take advantage of these benefits and shift the data out.

5.2 using ATL data using OLE DB to use the program

As a result of direct access to the object of OLE DB database interface design and application requires a lot of code writing. To simplify programming, Visual C++ + + provides the ATL template data for the design of OLE DB applications and data provider.

ATL template use can be easily combined with OLE DB and MFC, so that the parameters of the database query, such as the complexity of the programming has been simplified. MFC provides a database of categories so that OLE DB is more object-oriented programming features. Viual C++ + + provided by the ATL for the OLE DB data provider template process can be divided into the templates and data templates to use the program.

ATL template used to create data applications are the following general steps:

Application framework to create

Generated by adding ATL template classes

In the application of the use of the Data Access Objects

ATL do not use OLE DB data using the procedure

ATL template data generated using the procedure simpler to use, but not broad applicability and can not dynamically adapt to changes in the database. Us direct access to the following MFC OLE DB data type to generate the use of procedures.

The use of templates

OLE DB data users in the template is composed by a number of templates, including the following template, the following categories of some commonly used to make some introductory remarks.

Conversation Class

CDataSource category

CDataSource category and OLE DB data source object that corresponds to. This class represents the OLE DB data source provider and data connections between. Only when the data source connection has been established in order to have a session object, you can call the Open to open the data source connection.

CSession category

CSession object created on behalf of a single database access session. CDataSource a category created by the data source object can create one or more sessions to the data source object in a session object, the need to call functions Open () to open. At the same time, the conversation can also be used to create the transaction object operation.

CEnumeratorAccessor category

CEnumeratorAccessor enumeration type is used to access the device inquiry arising from the data line can be used to provide centralized access to the information process, and can provide the data currently available procedures and to provide accessors visible.

Class visit

CAcessor category

CAccessor representing the type of browser and access. When the user know the database type and structure, you can use this type. It supports a multi-rowset accessor and storage of data buffer is allocated by the user.

CDynamicAccessor category

CDynamicAccessor type used in the procedure to create a dynamic run-time access to device. When the system is running, you can dynamically get out from the line focus of the information, this information can be dynamically created accessor.

CManualAccessor category

CManualAccessor class run-time in the program will be included with the bind variables or parameters and variables will be set bundle.


CRowSet category

CRowSet rowset class encapsulates the object and the corresponding interface, and provides a number of methods for the inquiry, set up data. Can be used Move () function to record, such as mobile, the GetData () function to read data, using Insert (), Delete (), SetData () to update the data.

CBulkRowset category

CBulkRowset category for a call back in a number of firms handle or operate on a number line.

CArrayRowset category

CArrayRowset class provides an array subscript used for data access.

Class orders

CTable category

CTable categories for easy access to the database, using the name of the data source row has been set, in order to get the data.

CCommand category

Class CCommand order to support the data source. Can be used Open () function to execute SQL commands can also be Prepare () function first to prepare an order for the data source to support the order, the procedure can improve the flexibility and robustness.

In the stdafx.h header file to add the following code.

# include

extern CComModule _Module;

# include

# include

# include / / if you are using schema templates

In stdafx.cpp document, by adding the following code.

# include

CComModule _Module;

Decided to use what type of access procedures and rowset.

Access to data

Open data source, session, set the target line after the data available. Type of data obtained depends on the procedures used to access, you may need to bind out. By the following steps.

With the correct command to open rowset object.

If you use CManualAccessor, before the use of columns with the corresponding binding. To bind out, you can use function GetColumnInfo, as follows:

/ / Get the column information

ULONG ulColumns = 0;



if (rs.GetColumnInfo (& ulColumns, & pColumnInfo, & pStrings)! = S_OK)

AfxThrowOLEDBException (rs.m_pRowset, IID_IColumnsInfo);

struct MYBIND * pBind = new MYBIND [ulColumns];

rs.CreateAccessor (ulColumns, & pBind [0], sizeof (MYBIND) * ulColumns);

for (ULONG l = 0; l

rs.AddBindEntry (l +1, DBTYPE_STR, sizeof (TCHAR) * 40, & pBind [l]. szValue, NULL, & pBind [l]. dwStatus);

rs.Bind ();

Use while loop to check the data. In the cycle, call MoveNext to test whether the return value of the cursor for S_OK, as follows:

while (rs.MoveNext () == S_OK)


/ / Add code to fetch data here

/ / If you are not using an auto accessor, call rs.GetData ()


While circulating in, you can access through different procedures to obtain data.

If you are using CAccessor category, you can through the use of their direct access to data members. As follows:

If you are using CDynamicAccessor or category CDynamicParameterAccessor can GetColumn function GetValue or to obtain data. GetType can be used to obtain data types. As follows:

while (rs.MoveNext () == S_OK)


/ / Use the dynamic accessor functions to retrieve your

/ / Data

ULONG ulColumns = rs.GetColumnCount ();

for (ULONG i = 0; i


rs.GetValue (i);



If you are using CManualAccessor, you can specify their own data members, bind them. Can directly access. As follows:

while (rs.MoveNext () == S_OK)


/ / Use the data members you specified in the calls to

/ / AddBindEntry.

wsprintf ( "% s", szFoo);


Bank decided to set the data type

Decision in the run-time data types, dynamic or manual use of the access procedures. If you are using a hand-access procedures can be GetColumnInfo function column rowset of information. From here can be data types.

5.4 summary

Because there are a variety of data sources, and wants access to these data is the only way to manage through a number of similar mechanisms to achieve, such as OLE DB. Senior OLE DB structure is divided into two parts: clients and providers. Customers generated by the data providers.

Like other COM-based, like most of the structure, OLE DB developers need to achieve a lot of interfaces, most of which are template files.

When generating a client object, can point to a ATL Object Wizard to create a data source and simple customers. ATL Object Wizard will check the data source and create a database agent clients. From there, through OLE DB client browser using the standard template function.

When to generate a provider, the wizard provides a good starting point, they only generate a simple list of providers to document in a directory. Then, the template provider to support the OLE DB contains the complete content added. In this support, users can create OLE DB providers, to achieve rowset positioning strategies, to read and write data and the establishment of a bookmark.

6, the use of ADO

6.1 Overview

ADO is ActiveX Data Objects (ActiveX Data Object), this is the Microsoft development of database applications of the new object-oriented interface. ADO to access the database through the OLE DB data access procedures, and provides an OLE DB data provider of high-level visits of the simple interface.

ADO technology simplifies OLE DB operation, OLE DB procedures for the use of a large number of COM interfaces, and the ADO interface package. Therefore, ADO is a high-level access technology.

ADO object model is based on the common (COM), which provides multilingual access to technology, at the same time, due to ADO Access Automation Interface provides, therefore, ADO can be used to describe the scripting language to access VBScript, VCScript and so on.

6.2 the use of ADO in vc

VC6 can use ActiveX controls provided by the development of applications, ADO objects can also be used to develop applications. ADO objects use development applications so that developers can more easily control access to the database, thereby creating demand in line with the user database access procedures.

ADO objects use similar procedures for the development and application of other technologies, have to be connected with the data source, create a record of such steps, but with other access technology is different, ADO technology to target levels and between the relationship between the requirements of the order is not too strict. In the development process of the election do not have to establish a connection, and then have a record to object. Can be recorded in the use of direct access to records of local objects, objects in the creation of records at the same time, the program automatically create a connection with the data source. This model simplifies the procedures for effective design, enhanced the flexibility of the proceedings. The following objects on the use of ADO programming approach.

6.21 introduction of ADO library file

The use of ADO in the works before the stdafx.h file to use # import direct introduction of the introduction of ADO symbol library file, so the compiler to compile correctly. Code as follows:

# define INITGUID

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

# include "icrsint.h"

Statement to this statement in the works to use ADO, but ADO does not use the name space, and in order to avoid conflict, the EOF changed its name to EndOfFile.

ADO initialization environment 6.22

In the use of ADO objects must be initialized before the COM environment. Initialize COM environment can be completed with the following code:

:: CoInitialize (NULL);

Initialize COM in the environment, you can use ADO objects, and if the procedure did not add this code in front, will have a COM error.

End the use of ADO objects, the need to use the following code to initialize the object of the release:

:: CoUninitialize ();

This function is cleared to prepare for the COM object ADO environment.

6.23 Interface Profile

ADO library contains three basic interface:

__ConnectionPtr Interface,

__CommandPtr Interface,

__RecordsetPtr Interface,

__ConnectionPtr Interface returns a recordset or a null pointer. Usually use it to create a data connection or the enforcement of a non-return of any results of SQL statements, such as a stored procedure. __ConnectionPtr Interface with the return of a recordset is not a good use. CDatabase usually the same as using it to create a data connection, and then use other objects to implement data input and output operations.

__CommandPtr Interface returns a recordset. It provides a simple approach to the implementation of the return of the stored procedure recordset and SQL statements. In the use of __CommandPtr interface, you can use the overall __ConnectionPtr interface, __CommandPtr interface can also use the connection string directly. If only the implementation of one or several data access operation, which is a better choice. But when it comes to frequently access the database, and a lot of records set to return, then the interface should be used to create a global __ConnectionPtr data connection, and then use stored procedures to implement __CommandPtr interface and SQL statements.

__RecordsetPtr Is a recordset object. Compared with these two kinds of object, set its record of providing more control functions, such as record locking, cursor control. __CommandPtr Interface with, it does not necessarily have to have been created using a data connection, can be used in place of a connection string to connect the connection pointer __RecordsetPtr members assigned to variables, let it create a data connection. If you want to use multiple record sets, the best way is to use the Command object has been created as a data connection-ConnectionPtr global interface, then use the stored procedure implementation __Recordse7tPtr and SQL statements.

6,24 access the database using ADO

__ConnectionPtr Is a connection interface, the first instance to create a __ConnectionPtr interface, and then point to and open an ODBC or OLE DB data source data providers (Provider). , Respectively, the following code to create a DSN and DSN-based data connections.

/ / Use __ConnectionPtr (based on the DSN)

__ConnectionPtr MyDb;

MyDb.CreateInstance (__uuidof (Connection));

MyDb-> Open ( "DSN = samp; UID = admin; PWD = admin ","","",- 1);

/ / Use-ConnectionPtr (based on non-DSN)

__ConnectionPtr MyDb;

MyDb.CreateInstance (__uuidof (Connection));

MyDb.Open ( "Provider = SQLOLEDB; SERVER = server; DATABASE = samp; UID = admin; PWD = admin ","","",- 1);

/ / Use the implementation of SQL statements __RecordsetPtr

__RecordsetPtr MySet;

MySet.CreateInstance (__uuidof (Recordset));

MySet-> Open ( "SELECT *  FROM some__table", MyDb.GetInterfacePtr (), adOpenDynamic, adLockOptimistic, adCmdText);

Now we have a data connection and a recordset, then you can use data. Can be seen from the following code, the use of ADO's __RecordsetPtr interface, you do not need as frequent use of DAO as large and complex data structure VARIANT, and cast a variety of data types, and this is one of the advantages of ADO. Procedures assume that there is a name of the ListBox control m__List, we use the following code __RecordsetPtr record set data access interface and fill the ListBox control:

__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 error !");}

Used in the code must always try and catch to catch errors ADO, ADO error otherwise your application will crash. When running ADO error occurred (such as a database does not exist), OLE DB data provider will automatically create a __com__error object, and fill the relevant error message to the members of the target variable.

6.25 Type Conversion

COM object is as a result of cross-platform, which uses a common approach to dealing with all types of data, the CString class and COM objects are not compatible, we need to transform a set of COM object API and C + + types of data. __bstr__t is __vatiant__t and two objects. They provide a common method of conversion COM objects and C + + types of data.

6.3 in vb using ADO

ADO provides the following ways:

1, connected to the data source. At the same time, the data to determine the source of all the changes have been successful or did not happen.

2, the specified command to access the data sources, with variable parameters at the same time, optimizing the implementation.

3, the implementation of the order.

3, if the command data in table form in the return line, these lines will be stored in a readily accessible for inspection, operation or changes to the cache.

4, where appropriate, can be used to change the contents of the cache line to update the data source.

5, conventional methods to provide error detection (usually by establishing a connection or result in the implementation of the order).

In a typical case, the need to use programming model for all these steps. However, due to the flexibility of ADO strong, so only the implementation part of the final module will be able to do some useful work.

The following ADO programming model elements are key parts:

Connect 6.31

Through the "Connect" from the application can access the data source connection is necessary for the exchange of data environment. Connection object using the object model to connect the concept to make concrete.

"Services" is used to define the process of connecting a series of data access in the beginning and end of the operation. ADO can be clearly affairs caused by the operation of the data source or the success of the changes occurred or did not happen. If there is no business or the failure of one of its operations, the end results will be as if the operation of affairs did not occur, the data source will be maintained before the start of the state of affairs. Object model can not clearly reflect the concept of services, but with a Connection object to that. ADO from the OLE DB provider to access the data and services. Connection object is used to specify a provider of specialized and arbitrary parameters.

6.32 order

The connection has been established through the issue of the "order" can be operated in one way or another data source. Under normal circumstances, the data source in order to add, delete, or update data, or line in the table format to retrieve data. Command object with object model to reflect the concept of order. ADO can use the Command object to optimize the implementation of the order.


Typically, the variable part of the command needs the "parameters" can be carried out in order to change before publication. For example, you can duplicate the same data retrieval command, but can change every time the specified retrieve information.

Parameters on the activities and functions the same executable command is very useful, so you can know that the order is doing, but do not know how to work it. For example, a bank may issue a transfer order, the other loans from the lending side. Can transfer the amount to be set to the parameters.

Parameter objects use object model to reflect the parameters of the concept.

6.33 recordset

If the order is based on information in the table row of the query to return data (trip back to query), then these will be stored in the local.

Embodiment of the storage object model for the Recordset object. However, there is no representative of only a single line of the Recordset object.

Record set is good to check and modify the data in the most important method.

634 field

Line set a record contains one or more "field." If the recordset as a two-dimensional grid, with the field will constitute a "out." Each field (column) are, respectively, contain the name, data type and value of the property is included in the value of the data source from the real data.

Field Target object model to reflect the field.

To modify the data source data line can be set in the record to modify the value of Field object on the record transmitted to the final changes to the data source. As an option, Connection object management method can reliably ensure that all changes to either the success or total failure.

6.35 error

Error in the application at any time may occur, usually can not establish a connection as a result of the implementation of an order or for certain state (for example, trying to use the non-initialization of the recordset) to operate the object.

Error Object object model to reflect the error.

Any given error will have one or more Error objects, then error will be generated by the Error object to give up the previous group.

6.36 Properties

Each object has a set of ADO only "attributes" to describe the conduct or control.

Built and dynamic properties of two types. Built-in attribute is part of ADO objects and can be used at any time. Dynamic properties from the data providers in particular added to the ADO object collection, the only provider to be used only when there is.

Property object model to reflect the attributes object.

6.37 set

ADO to provide "set", which is a convenient object that contains other special types of object type. Collection methods can be used name (text string) or number (integer) to set the target of retrieval.

ADO provides four types of collections:

Connection with the Errors collection of objects, including data sources and in response to the creation of a single error and all the Error object.

Command object has a Parameters collection, including the Command object applies to all the Parameter object.

Recordset object has a Fields collection that contains all the definitions out of the Field object Recordset object.

In addition, Connection, Command, Recordset and Field objects have a Properties collection. It contains all the objects are all included in the Property object.

ADO object may have used such as "integer", "character" or "Boolean" data type so common to set or retrieve the value of the property. However, it is necessary to some of the attributes as a data type "COLLECTION OBJECT" the return value. Accordingly, the collection of objects with appropriate storage and retrieval of other objects in the collection method.

6.38 events

ADO 2.0 to support the event, the operation of certain events to be notified or have already occurred.

There are two types of events: ConnectionEvent and RecordsetEvent. Connection objects have ConnectionEvent events, and Recordset objects have events RecordsetEvent.

Events by the event handler routine processing, the routine operation in a before or after the end of the beginning is called.

Certain events occur in pairs. Commencement of operation of the incident before the call format of WillEvent (Will the incident), and the operators of the incident after the end of the format called for EventComplete (Complete events). The rest not only on the events occurring after the end of the operation. (Its name there is no fixed pattern.) Event handler controlled by the state parameters. Additional information from the error and the object parameter.

May request the event handler does not accept the first time after having been informed of any notice. For example, you can choose to receive only events or Complete Event Will.

The following code shows an example of the use of ADO.

First of all, adding Microsoft ActiveX Data Object 2.0 Library reference.

Dim db As Connection

Set db = New Connection

db.CursorLocation = adUseClient

db.Open "PROVIDER = MSDASQL; DSN = TestDatabase", "sa", "", -1

Dim i As Long

Dim id As Long

Dim value As Single

Dim rst As New Recordset

Set rst = New Recordset

rst.Open "select * from simulated changes in the history of table", db, adOpenDynamic, adLockOptimistic


For i = 0 To rst.RecordCount - 1

id = rst.Fields ( "ID")

value = rst.Fields ( "VALUE")


Next i


Set rst = Nothing


6.4 summary

ADO to access the database technology is a new technology, with easy-to-use, flexible access to a wide range of features. Using ADO to access the data source characteristics can be summarized as follows:


ADO technology, which is one of the most important characteristics. ADO is a high-level as a result of the application, so as opposed to OLE DB or ODBC, it has the characteristics of object-oriented. At the same time, the object of the structure of ADO, the object-level relations between the not obvious. DAO access in relation to technical terms, etc., but also do not have to care about the structure of the target sequence and structure levels. For the use of the object, do not choose to establish a connection, conversation and other objects, can only direct structure to facilitate the preparation of the application.

High-speed access to data source

As a result of ADO technology is based on OLE DB, so, it also inherited the OLE DB high speed access to the database.

Be able to access different data sources

ADO technology, including relational database may be accessed and non-relational database of all the file system. This is a feature so that applications have a lot of flexibility and versatility.

Microsoft ActiveX can be used to page

ADO technology in the form of ActiveX controls, so can be used for Microsoft ActiveX pages, this feature of WEB-page to simplify programming.

Procedures less memory

Because ADO is based on the Component Object Model (COM) of the access technology, so, using ADO applications have less memory.

7, summed up

To access the data should be used when the judge what kind of technology, which is not easy. Public utility may need to deal with multiple database types; part of the data may appear in the local hard drive, some on the network, as well as part of the host. Customers and even install the product on the device will make this option more difficult. For example, your ODBC expected level of support may depend on the installed version of Microsoft Office, because the product does not provide ODBC support. You will also discover, ADO object type and methods provided by Multi-than ODBC. ADO procedures can provide absolute must have some characteristics such as date, you will find that OLE-DB and ADO support both DFX_Currency, but there is no corresponding ODBC functions, but if you want to grasp that they will have to pay a lot of efforts.

Choice of ODBC or OLE-DB, there were a few general rules. ADO because it is just a OLE-DB package, these rules also apply to it. Here are some basic principles that can be used to help you decide which option to OLE-DB or ODBC.

Non-OLE environment to support the ODBC database access, and the database does not support OLE in the server, then the ODBC is the best choice.

ODBC non-SQL environment when dealing with SQL very well. To deal with non-SQL database, OLE-DB has a very distinct advantage.

OLE environment OLE server support, the choice of ODBC or OLE-DB may be half hope. If there are ODBC drivers available, then the use of ODBC is a good idea; Otherwise, the only choice of the OLE-DB.

Interoperability requirements, if necessary interoperable database components, then the only choice is OLE-DB.

C/C++ Tutorial Articles

Can't Find What You're Looking For?

Rating: Not yet rated


No comments posted.