Detailed description of configuring the data source and connecting to ACCESS through VC ++ ADO

Source: Internet
Author: User
# Includeiostream. h # importc: programfilescommonfilessystemadomsado15.dllno _ namespacerename (EOF, adoEOF) the dll required for connecting to the database from ADO. during compilation, the system will generate msado15.tlh for us, ado15.tli two C header files to define the ADO library. Note that the import here must be placed

# I nclude iostream. h # import c:/program files/common files/system/ado/msado15.dll no_namespace rename (EOF, adoEOF) // dll required for connecting to the database by ADO, during compilation, the system will generate msado15.tlh for us and the ado15.tli two C header files to define the ADO library // note that the import here must be placed

# I nclude
# Import "c:/program files/common files/system/ado/msado15.dll" no_namespace rename ("EOF", "adoEOF ")
// The dll required by ADO to connect to the database. during compilation, the system will generate msado15.tlh and ado15.tli two C ++ header files for us to define the ADO library.
// Note that the import here must be placed in a row

Int main (){

// This program uses ADO to connect to ACCESS (which is included when the office is installed). The database suffix is. mdb running platform vc6.0.
// 2003 the Platform says
//---------------------------------------------------------------------------------

// The ADO database is connected in five steps,
// First, obtain the connection (only to where the database is located)
// Second, open the connection (required username and password)
// Third, obtain the character set ResultSet (similar to the data storage object of arrays ),
// Fourth, display data
// Fifth, close the dataset and close the connection

// Create a connection object
_ ConnectionPtr m_pConnection;

// Initialize the connection
CoInitialize (NULL );

//---------------------------------------------------------------------------------
// Step 1. Obtain the connection
//---------------------------------------------------------------------------------
// Create and obtain a database Connection instance with the same Connection,
// You can also think of him as a handle (for movie tickets), so that he is eligible to use the resources in the database.
M_pConnection.CreateInstance (_ uuidof (Connection ));

// Errors may occur during database connection, such as data source setting or incorrect user name and password.
// Use try {...} catch () {...} to catch exceptions (errors) in try)
// And put these exceptions in the Variable _ com_error e. We can get the error information with him.
// In addition, when an error occurs, the program must run catch () {...}. We can see that if a connection error occurs
// Cout <"database connection failed. Check whether mydb. mdb is in the current path! "< // Return FALSE; a program will be launched later. If you do not add a try, the system will crash when a program error occurs.
// Therefore, try can also be seen as an error handling (Exception Handling)
Try
{//---------------------------------------------------------------------------------
// Step 2. Open the connection parameters and separate them.
//---------------------------------------------------------------------------------

// Provider = Microsoft. Jet. OLEDB.4.0; access vendor
// Data Source = mydb. mdb "," "," ", adModeUnknown Database Name, username (blank), password (blank), default connection mode
// For this parameter: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ (1)
/* AdModeUnknown: default. The current permission is not set
AdModeRead: Read-Only
AdModeWrite: Write only
AdModeReadWrite: read/write
AdModeShareDenyRead: blocks other Connection objects and opens the Connection with the read permission.
AdModeShareDenyWrite: blocks other Connection objects and opens the Connection with write permission.
Admodemo-exclusive: prevents other Connection objects from opening connections.
AdModeShareDenyNone: allows other programs or objects to establish connections with any permissions.
*/
// Through this statement, our database connection is actually implemented. m_pConnection has content (value attached)
M_pConnection-> Open ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source = mydb. mdb", "", "", adModeUnknown );

}
Catch (_ com_error e) // catch exceptions
{
Cout <"database connection failed. Check whether mydb. mdb is in the current path! "< Return FALSE;
}

// DataSet object
_ RecordsetPtr m_pRecordset;
// Instantiate a dataset
M_pRecordset.CreateInstance (_ uuidof (Recordset ));

//---------------------------------------------------------------------------------
// Step 3: Obtain the dataset
//---------------------------------------------------------------------------------
// Although the connection is established, whether there is a data table (test table) in the connected database is unknown.
// Therefore, it is also necessary to capture Possible Errors
Try
{
M_pRecordset-> Open ("SELECT * FROM test", // It is a data query string (the so-called SQL statement)
// These statements are usually divided into data query (select) and insert (insert) statements)
// Update and delete)
// Whether the command can be executed is determined by the preceding (1 ).

M_pConnection.GetInterfacePtr (), // gets the IDispatch pointer of the database connected to the database

AdOpenDynamic, // dynamic cursor. All database operations will be immediately reflected in each user record set

AdLockOptimistic, // Optimistic Locking mode. The record is locked only when you call the Update method. Here
// You can still update, insert, or delete data.

AdCmdText); // The queried data is displayed on the console.
}
Catch (_ com_error * e)
{
Cout < ErrorMessage () < }

_ Variant_t var;
Char * ID, * name;

Try // obtain the table, but the table does not necessarily have data
{
If (! M_pRecordset-> BOF) // The data table contains data.
M_pRecordset-> MoveFirst (); // move the cursor (the dataset name in the database) to the first record.
Else {
Cout <"table data is empty" < Return 1;
}


// Configure //--------------------------------------------------------------------------------------------------------------------------
// Step 4: Display Data
// Configure //---------------------------------------------------------------------------------------------------------------------------

While (! M_pRecordset-> adoEOF) // corresponds to the previous rename ("EOF", "adoEOF ").
// AdoEOF replaces EOF (of course, you can also use EOF if there is no rename above)
// Determine whether the cursor has reached the last data entry
{
Var = m_pRecordset-> GetCollect ("ID"); // This is a method for obtaining fields in a table. "ID" indicates the table field name.
If (var. vt! = VT_NULL) // determines whether the record has no data.
ID = _ com_util: ConvertBSTRToString (_ bstr_t) var); // conversion is required because the data obtained may not contain characters.
// Convert them into strings so that they can be displayed on the screen

Var = m_pRecordset-> GetCollect ("name ");
If (var. vt! = VT_NULL)
Name = _ com_util: ConvertBSTRToString (_ bstr_t) var );

Cout <
M_pRecordset-> MoveNext (); // The cursor moves toward the next record
}
}
Catch (_ com_error * e) // catch exceptions
{
Cout < ErrorMessage () < }
// Configure //--------------------------------------------------------------------------------------
// Close the dataset
// Configure //-----------------------------------------------------------------------------------
M_pRecordset-> Close ();
M_pRecordset = NULL;

// Configure //--------------------------------------------------------------------------------------
// Close the database connection
// Configure //--------------------------------------------------------------------------------------
If (m_pConnection-> State)
M_pConnection-> Close ();
M_pConnection = NULL;

// These two steps must be done. Otherwise, the memory may be exhausted for a long time.
Return 0;
}

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.