VC uses ADO components to access the database program design

Source: Internet
Author: User
When VC is involved in connecting to the database, I have not used VC to connect to the database before. I read the source code and learned a little about it. I think the general connection method is as follows: i. ADO overview ADO is an easy-to-use application layer interface designed by Microsoft for the latest and most powerful data access example OLEDB. ADO enables you to write applications

When VC is involved in connecting to the database, I have not used VC to connect to the database before. I read the source code and learned a little about it. I think the general connection method is as follows: i. ADO overview ADO is an easy-to-use application layer interface designed by Microsoft for the latest and most powerful data access example OLE DB. ADO enables you to write applications

When VC is involved in connecting to the database, I have not used VC to connect to the database before. I read the source code and learned a little about it. I think the general connection method is as follows:

I. ADO Overview
ADO is an easy-to-use application layer interface designed by Microsoft for the latest and most powerful data access example ole db. ADO enables you to write applications to access and operate data on database servers through the OLE. DB Provider. The main advantages of ADO are ease of use, fast speed, low memory consumption, and small disk relics. ADO uses the least network traffic in key application solutions, and uses the least number of layers between the front end and the data source. All these are designed to provide lightweight, high-performance interfaces. ADO is a familiar metaphor for OLE Automation interface.

Ole db is a set of "Component Object Model" (COM) interfaces. It is a new low-level database interface that encapsulates ODBC functions, access data stored in different information sources in a unified manner. Ole db is the technical basis for Microsoft UDA (Universal Data Access) policies. Ole db provides high-performance access to any data source, including relational and non-relational databases, e-mail and file systems, text and graphics, and custom business objects. That is to say, ole db is not limited to ISAM, Jet, or even relational data sources. It can process any type of data without considering their format and storage methods. In practical applications, this diversity means that you can access data that resides in an Excel spreadsheet, text file, email/directory service, or even a mail server, such as Microsoft Exchange. However, the ole db Application Programming Interface is designed to provide the best functions for various applications and does not meet the simplification requirements. The API you need should be a bridge between applications and ole db, Which is ActiveX Data Objects (ADO ).

2. Use ADO in VC (the development steps are as follows :)

1. Introduce the ADO Library File

First, use the # import command in StdAfx. h to introduce the ADO database. The statement is as follows:

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

Here, EOF indicates the end of the file. We will use BOF in later application. It is readable for the file without any content, that is, before of file.

This statement declares that ADO is used in the project, but the namespace of ADO is not used. To avoid constant conflicts, change the constant EOF to adoEOF. Now you can use the ADO interface without adding another header file.

2. initialize the OLE/COM library Environment
Note that the ADO library is a group of COM dynamic libraries, which means that the application must initialize the OLE/COM library environment before calling ADO. In an MFC application, a better method is to initialize the OLE/COM library environment in the InitInstance member function of the main class of the application.
BOOL CMyApp: InitInstance ()
{
If (! AfxOleInit () // This is the initialization COM Library
{
AfxMessageBox ("OLE initialization error !");
Return FALSE;
}

......

}

Declare a _ ConnectionPtr myCon in the CMyapp class; myCon is used to connect to the database, and InitInstance () in the CMyapp ()

Code:

BOOL CMYApp: InitInstance ()

{

.

.

.

AfxOleInit (); // ado interface Initialization
MyCon. CreateInstance (_ uuidof (Connection); // Connection initialization, get pointer to SQL

// You can also read the script file below to obtain other information about connecting to the database,

}

Then, declare a _ RecordsetPtr myRecordset in the corresponding classes of the dialog box. Use this myRecordset to connect to the table. Note that after each table is connected, open () and close () immediately after use ()

In the OnInitDialog () function of the dialog box

OnInitDialog ()

{

MyRecordset. CreateInstance (_ uuidof (Recordset); // create a connection instance

// MyRecordset. CreateInstance ("ADODB. Recordset ")
// In the ADO operation, we recommend that you use try... catch () to capture error information,
// Because it often produces unexpected errors.

CCarApp * pApp = (CCarApp *) AfxGetApp ();
MyRecordset-> put_CursorLocation (adUseClient); // set the cursor to the client status

MyRecordset-> Open ("SELECT distinct vehicle id from vehicle information", pApp-> myCon. GetInterfacePtr (), adOpenDynamic, adLockOptimistic, adw.text );

The meanings of parameters of the open () function are SQL statements, SQL connection pointers, and the following three are defined constants, which have the following meanings:

// Const adOpenDynamic = 2' the most dynamic cursor function, but the most resource consumption. The added or deleted records modified by the user on the record description will be reflected in the record set. Supports full-featured browsing
// Const adLockOptimistic = 3' the record set is locked only when the Update method is called, and other operations before this can still change, insert, and delete the current record
// AdCmdText uses CommandText as the compile definition of the command or stored procedure call for calculation.

For the significance of the open () function, see the http://hi.baidu.com/ruiqing_2008/blog/item/50381334c10183bbd1a2d369.html

In this way, you can use the cursor to query data and use CString to save the queried data.

CString s1;

While (! MyRecordset-> adoEOF)
{
S1 = (char *) (_ bstr_t) (myRecordset-> Fields-> GetItem (_ variant_t ("vehicle ID")-> Value );

// When the queried data is saved in s1, you can assign s1 to control variables and other operations.
(CComboBox *) GetDlgItem (IDC_COMBO3)-> AddString (s1 );//

MyRecordset-> MoveNext (); // move to the next record

// How to query variant data
// _ Variant_t varNo;
// VarNo = myRecordse-> GetCollect ("vehicle ID ");
// CString strNo = (char *) _ bstr_t (varNo );

}

// Close the table

MyRecordset-> Close ();

In addition, you can use the Active Control DBGrid Control to save the data in the table and define a variable m_grid of the CDataGrid class for the Control;

Bind a data source to OnInitDialog () in the dialog box.

M_grid.SetRefDataSource (NULL );
M_grid.SetRefDataSource (LPUNKNOWN) myRecordset); // bind the implementation to the DBGRID control. myRecordset has been connected to the database just now.
M_grid.Refresh ();

}

In the specific query process, we only need to obtain data through the interface.

MyRecordset-> MoveFirst (); move to the first record

MyRecordset-> Move (-1); Move to the previous record

MyRecordset-> MoveNext (); move to the next record

MyRecordset-> MoveLast (); move to the end of the record

MyRecordset-> AddNew (); adds a new record

This-> myRecordset-> Delete (adAffectCurrent); Delete this record

When adding a new record, we can get the content of the edited edit box and write it to the database.

CString s1;
GetDlgItemText (IDC_EDIT1, s1); // get the content of the edit box and save it to s1

Write Data Set

MyRecordset-> PutCollect ("vehicle ID", (variant_t) s1); // Add data to the corresponding column

Query code

If (myRecordset-> adoEOF) // end of the Set
{
Return;
}
If (myRecordset-> BOF) // before of file
{
Return;
}

// The above indicates no content or query

CString s1;
S1 = (char *) (_ bstr_t) (myRecordset-> Fields-> GetItem (_ variant_t ("vehicle ID")-> Value );

// The queried variant data is forcibly converted and saved to s1
This-> SetDlgItemText (IDC_EDIT1, s1); // set the vehicle information in the corresponding editing box to s1

// The following describes the use of the ADO interface written in TOTO.

3. Introduction to ADO Interfaces

The ADO library contains three basic interfaces: _ ConnectionPtr, _ CommandPtr, and _ RecordsetPtr.
_ ConnectionPtr interface returns a record set or a null pointer. It is usually used to create a data connection or execute an SQL statement that does not return any results, such as a stored procedure. Using the _ ConnectionPtr interface to return a record set is not a good method. _ RecordserPtr is usually used for operations to return records. When you use the _ ConnectionPtr operation, you need to retrieve the number of records to traverse all records, but you do not need to use the _ RecordserPtr operation.

The _ CommandPtr interface returns a record set. It provides a simple method to execute stored procedures and SQL statements that return record sets. When using the _ CommandPtr interface, you can use the global _ ConnectionPtr interface, or you can directly use the connection string in the _ CommandPtr interface. If you only perform one or several data access operations, the latter is a good choice. However, if you want to frequently access the database and return many record sets, you should use the global _ ConnectionPtr interface to create a data connection, use the _ CommandPtr interface to execute stored procedures and SQL statements.

_ RecordsetPtr is a record set object. Compared with the above two types of objects, it provides more control functions for the record set, such as record lock and cursor control. Like the _ CommandPtr interface, it does not have to use a created data connection. You can use a connection string to replace the connection pointer with the connection Member variable assigned to _ RecordsetPtr, create a data connection by yourself. If you want to use multiple record sets, the best way is to use the global _ ConnectionPtr interface that has created a data connection like the Command object.
And then use _ RecordsetPtr to execute stored procedures and SQL statements.

4. Use the _ ConnectionPtr Interface
_ ConnectionPtr is mainly a connection interface that gets a connection to the database. Its connection string can be directly written by itself or directed to an 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. Use the _ RecordsetPtr interface (taking connecting to SQL Server as an example)
_ 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, adshorttext )))
{
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. Use the _ CommandPtr Interface
The _ CommandPtr interface returns A Recordset object and provides more record set control functions. The following code example shows how to use the _ CommandPtr interface:

Code: Use the _ CommandPtr interface to obtain data
_ CommandPtr pCommand;
_ RecordsetPtr pRs;
PCommand. CreateInstance (_ uuidof (Command ));
PCommand-> ActiveConnection = pConn;
PCommand-> CommandText = "select * from student ";
PCommand-> CommandType = ad1_text;
PCommand-> Parameters-> Refresh ();
PRs = pCommand-> Execute (NULL, NULL, adCmdUnknown );
_ Variant_t varValue = pRs-> GetCollect ("name ");
Cstring strValue = (char *) _ bstr_t (varValue );


7. For data type conversion, because the COM object is cross-platform, it uses a common method to process various types of data. Therefore, the Cstring class is incompatible with the COM object, we need a set of APIs to convert data of the COM Object and C ++ type. _ Vatiant_t and _ bstr_t are two types of objects. They provide common methods to convert data of the COM Object and C ++ type.

Source code is the best teacher

The database server has not been configured, so it has not been tracked and tested. Try configuring the database in two days.

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.