The ADO chapter of VC Database Foundation development

Source: Internet
Author: User
Tags dsn odbc ole

The ADO chapter of VC Database Foundation development
--------------------------------------------------------------------------------

Join time: 2003-9-2 9:14:02 Source: Little Software Park Browse 137 times

--------------------------------------------------------------------------------

I. INTRODUCTION of ADO
ADO (ActiveX Data Object) is a new interface developed by Microsoft database applications and is a high-level database access technology built on OLE DB, so you don't have to worry about it, even if you don't know OLE db,com and you can easily deal with ADO. Because it's so easy to use, it's even easier to work with than the ODBC API, DAO, and RDO you've been exposed to before, without sacrificing flexibility. This article will describe in detail how to use ADO for database application development under VC, and give sample code.
The sample code for this article

Second, the basic process
Everything is difficult at first, and any new technology is the most important thing for beginners to learn about the basics. Let's take a look at the basic flow of ADO database development!
(1) Initialize the COM library and introduce the ADO library definition file
(2) Connect database with Connection object
(3) Make use of established connection, execute SQL command through connection, command object, or use Recordset object to obtain result recordset for query and processing.
(4) Close the connection release object after the use is complete.

Preparatory work:
For everyone to test the examples provided in this article, we use the Access database, or you can find this test.mdb directly in the sample code we provide.
Below we will describe the above steps in detail and give the relevant code.
Initialization of the "1" COM library
We can use AfxOleInit () to initialize the COM library, which is usually done in the overloaded function of CWinApp::InitInstance (), see the following code:


BOOL cadotest1app::initinstance ()
{
AfxOleInit ();
......

"2" introduces ADO type library with #import instruction
We add the following statement to the stdafx.h: (stdafx.h where can I find this file? You can find it in the header files of FileView)
#import "C:\Program Files\Common Files\system\ado\msado15.dll" No_namespace rename ("EOF", "adoeof")
How does this statement work? Its final function is similar to our familiar # include, when compiled, the system will generate a Msado15.tlh,ado15.tli two C + + header files to define the ADO library.

A few notes:
(1) Msado15.dll in your environment is not necessarily in this directory, please modify the actual situation
(2) The following warning will appear at compile time, which Microsoft has explained on MSDN and advises us to ignore this warning.
MSADO15.TLH (405): Warning c4146:unary minus operator applied to unsigned type, result still unsigned

"3" Creates a connection object and connects to the database
First we need to add a pointer to the connection object:
_connectionptr m_pconnection;
The following code shows how to create an Connection object instance and how to connect to the database and make exception snaps.


BOOL Cadotest1dlg::oninitdialog ()
{
CDialog::OnInitDialog ();
HRESULT hr;
Try
{
hr = m_pconnection.createinstance ("ADODB. Connection ")/////Create Connection Object
if (SUCCEEDED (HR))
{
hr = M_pconnection->open (" provider= Microsoft.jet.oledb.4.0;data Source=test.mdb "," "," ", admodeunknown);///Connect database
/// The above sentence in the concatenated string of Provider is for the ACCESS2000 environment, for ACCESS97, need to change: provider=microsoft.jet.oledb.3.51; }
}
catch (_com_error E)///catch exception
{
CString errormessage;
ErrorMessage. Format ("Connection database failed!\r\n error message:%s", E.errormessage ());
AfxMessageBox (errormessage);///Display error message
}

In this code we connect to the database through the open method of the Connection object, the following is the prototype of the method
HRESULT Connection15::open (_bstr_t ConnectionString, _bstr_t UserID, _bstr_t Password, long Options)
ConnectionString is the connection string, UserID is the user name, password is the login password, options is the connection option, to specify the connection object to update the data permissions,
The options can be several constants:
adModeUnknown: Default. The current license is not set
adModeRead: Read-only
adModeWrite: Write only
adModeReadWrite: can read and write
adModeShareDenyRead: Block other connection objects from opening connections with Read permissions
adModeShareDenyWrite: Block other connection objects from opening a connection with write permission
Admodeshareexclusive: Block other connection objects from opening the connection
adModeShareDenyNone: Allow other programs or objects to establish connections with any permissions

We give some common connection methods for your reference:
(1) connection to the ACCESS2000 database through the Jet database engine

M_pconnection->open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test.mdb", "" "," ", AdModeUnknown);

(2) Connect to any ODBC-enabled database through a DSN data source:
M_pconnection->open ("Data source=adotest; Uid=sa; pwd=; "," "," ", adModeUnknown);

(3) Do not connect to the SQL Server database through DSN: M_pconnection->open ("Driver={sql Server}; Server=127.0.0.1;database=vckbase; Uid=sa; pwd=139 "," "," ", adModeUnknown);

Where server is the name of the SQL Server, database is the name of the library

Connection object There are many methods besides the open method, we first introduce two useful properties of connection object ConnectionTimeout and state
ConnectionTimeout is used to set the timeout for the connection, which needs to be called before Open, for example: m_pconnection->connectiontimeout = 5;///set timeout of 5 seconds
M_pconnection->open ("Data source=adotest;", "", "", adModeUnknown);


The State property indicates the status of the current connection object, 0 is off, 1 means it is already open, and we can do this by reading this property, for example:
if (m_pconnection->state)
M_pconnection->close (); If the connection is already open, close it


"4" Executes the SQL command and obtains the result recordset
To get the result recordset, we define a pointer to the Recordset object: _RecordsetPtr M_precordset;
and create an instance of the Recordset object for it: M_precordset.createinstance ("ADODB. Recordset ");
The execution of SQL commands can take many forms, as described below.

The ADO chapter of VC Database Foundation development

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.