Use ADO in MFC to ACCESS Microsoft's ACCESS database for addition, deletion, modification, and query

Source: Internet
Author: User
Tags try catch
ADO is a dynamic link library named msado15.dll on a hard disk. Step 1: Create a dialog box MFC program in VS2010. Step 2: Add a code in stdafx. h (The position is after the # includeafxdisp. hMFC automation class) # importC: ProgramFilesCommonFilesSystemADO

ADO is a dynamic link library named msado15.dll on a hard disk. Step 1: Create a dialog box MFC program in VS2010. Step 2: Go to stdafx. h. Add a code (the Add position is in # include afxdisp. h // After the MFC automation class) # import C: \ Program Files \ Common Files \ System \ ADO \



ADO is a dynamic link library named msado15.dll on a hard disk.


Step 1: Create a dialog box MFC program in VS2010.


Step 2: Add a code in stdafx. h (The position is after the # include // MFC automation class)


# Import "C: \ Program Files \ Common Files \ System \ ADO \ msado15.dll" no_namespace rename ("EOF", "EndOfFile ")


The following explains the meaning of the above Code.

# Import: "C: \ Program Files \ Common Files \ System \ ADO \ msado15.dll" means a full path, that is, msado15.dll.

The location of the file in the hard disk. If your system has not been deliberately changed, this path should be him.


What does no_namespace mean? Translation is notUseThe namespace is notUseThe component ADO has its own namespace. Otherwise, you will be behindUseWhen using some ADO Interfaces


You need to add something to the front? I don't know. I also stopped what others said)

Rename ("EOF", "EndOfFile"), even if you rename EOF, why do you need to rename it? This is becauseInsideThe word "EOF" is used, but the meaning is ADO.InsideThe EOF is not


It means that you need to rename it, or else ADO will be crazy. You can rename this as you like. Otherwise, you just need to rename it EndOfFile (some buddies like to name it ADOEOF)

# The import Statement is equivalent to executing the API culvert LoadTypeLib (). # The import Statement generates two files in the project executable program output directory: *. tlh (Type Library header file) and *. tli (Type Library file ).ImplementationFile), which generates smart pointers for each interface, declares various interface methods, enumeration types, CLSID, and creates a series of packaging methods.

××××××××××××××××××××××××××××××××××× × ×××××


Now, the second step is complete, and the third step is started.



Step 3: same as other component libraries in the worldUseBefore InitializationUseUnmount it later (this is what the teacher said)

How to initialize it.

You need to initialize components in the initial process of the program. Generally, you can use CoInitialize (NULL);ImplementationTo close the initialized COM at the end of this method, use the following statement CoUnInitialize ();Implementation. You can also use another method in MFC.ImplementationInitialize COM. Only one statement is required for this method.ImplementationTo disable the COM operation at the initialization and end, the statement is as follows:

AfxOleInit ()


To make the program more perfect, we recommend that you write it like this.

If (! AfxOleInit () // This is the initialization COM Library
{
AfxMessageBox ("OLE initialization error! ");
Return FALSE;
}


This function can be placed in the initialization function of TheApp object: InitInstance.

PS: if you do not know theapp's initialization function, click "X" in the upper-right corner of the page because this article is not suitable for you.



Step 4: make so many preparations that you can finally say the ADO.

First, let's take a look at the ADO stuff.Use.

ADO contains some top-level objects:
Connection, representingDatabaseConnection
Recordset, representingDatabaseA set of records
Command, representing an SQL Command
Record indicates a set of data.
Stream indicates the sequence set of data.
Error, which indicatesDatabaseAccessExceptions
Field representsDatabaseField
Parameter (Parameter), representing an SQL Parameter
Property to save the object information


I usually use the first three objects. I am not familiar with other things.


Step 5: create three objects in the MFC Dialog Box program, that is, the objects of the three smart pointers.

This object (whether it can be called an object or not) is input dialog box class

Is the result of my creation


Step 6: I created the three smart pointer objects.

It can be used after it is created. Where can I use it? Since these three objects belong to the dialog box class, you canUse.

Note that the following content is the core code.

First, let's talk about the overall idea of the core code.

A: LinkDatabaseB: Opening a record set is equivalent to usingDatabaseInsideSo far, the table exists in the memory.

C:UseRelated functions of ADOAdd/deleteModify query D: Disable record set E: disconnect

This completes a cycle.


Step 7: Create andDatabase.

OpenDatabaseIt can also be called a link.Database

Because data operations have a strong degree of uncertaintyDatabaseMost of the operations have error capture, that is, Try Catch.

HRESULT hr;
Try
{
// Create a connection instance first
Hr = m_pConnection.CreateInstance (_ uuidof (Connection); // create a Connection object
If (SUCCEEDED (hr ))
{
M_pConnection-> ConnectionTimeout = 600; // linkDatabaseTime Limit
M_pConnection-> CommandTimeout = 120; // it may be the SQL statement execution time limit
// Then openDatabaseParameters of OPEN functions are exquisite.
// Open a connection to the data source. When the connection is opened, You can execute commands on the data source.
// A string value that contains connection information. This string is composed of a series of parameter = value statements separated by semicolons.
// A string value, including the value required to establish a connectionUseUser name.
// A string value, including the value required to establish a connectionUsePassword.
// A value of ConnectOptionEnum to determine whether this method should be returned after the connection is established (synchronous) or before the connection is established (asynchronous.
Hr = m_pConnection-> Open ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source = Home. mdb", "", "", adModeUnknown );//
// The ConnectionString attribute has five parameters:
// Provider --- the name of the Provider used for connection.
// File Name --- the Name of a File (such as a persistent data source object) that is unique to the provider. These files contain preset connection information.
// Remote Provider -- when the client connection is enabledUseThe name of the provider. (Remote Data Service only .)
// Remote Server -- when the client connection is enabledUseThe path of the server. (Remote Data Service only .)
// Url --- indicates the absolute URL of a resource (such as a file or directory.
// Open Mode
/*
AdModeUnknown = 0,
AdModeRead = 1,
AdModeWrite = 2,
AdModeReadWrite = 3,
AdModeShareDenyRead = 4,
AdModeShareDenyWrite = 8,
Admodemo-exclusive = 12,
AdModeShareDenyNone = 16,
AdModeRecursive = 4194304
*/


}
}
Catch (_ com_error e) // catch an exception
{
CString errormessage;
Errormessage. Format ("ConnectDatabaseFailed! /R/n error message: % s ", e. ErrorMessage ());
AfxMessageBox (errormessage );///
}
AfxMessageBox ("opened successfullyDatabase");


Step 8: create a record set


M_pRecordset.CreateInstance (_ uuidof (Recordset ));
Try
{
M_pRecordset-> CursorLocation = adUseClient; // you need to transmit the data to the local device. For example, the application is disconnected.DatabasePerform the Recordset operation, that is, the operation in the memory
// Instead of writing data to the remote endDatabase. On the contrary, adUseServer directlyDatabase.
M_pRecordset-> Open ("SELECT * FROM Jianghu", // SQL statement
M_pConnection.GetInterfacePtr (),
AdOpenDynamic, // cursor type
AdLockOptimistic, // optimistic lock
AdCmdText); // command type
/*
When you open a Recordset for the first time, the current record pointer points to the first record, and the BOF and EOF attributes are False. If no record exists, the BOF and EOF attributes are True.


*/
}
Catch (_ com_error * e)
{
AfxMessageBox (e-> ErrorMessage ());
}
M_MyDataGrid.putref_DataSource (m_pRecordset); // function that links objects with the DataGrid Control. In VC6, SetRefDataSource
AfxMessageBox ("successfully opened record set ");

Step 9: Add rows to the table

//DatabaseOperation: add
// The cursor location andDatabaseThe primary key cannot be repeated. Otherwise, an error is returned.
// Step 1: Define four strings for obtaining data in the Edit control
CString ID = "2 ";
CString Name = "Fengqing ";
CString XingBie = "male ";
CString ZhaoShu = "Dugu jiujian ";
M_CEdit_ID.GetWindowTextA (ID); // obtain the text of the edit box, which is recorded in the szText variable.
M_CEdit_Name.GetWindowTextA (Name );
M_CEdit_Xingbie.GetWindowTextA (XingBie );
M_CEdit_ZhaoShu.GetWindowTextA (ZhaoShu );



// Step 2: perform operations on the database.
Try
{

// A: select the cursor position
M_pRecordset-> MoveFirst (); // the newly created data is added to the last row of the DataGrid.DatabaseInsideIs the first one.
// B: remind the system that I want to increase muscle data
M_pRecordset-> AddNew ();
// C: Call the PutCollect function to modify data.
M_pRecordset-> PutCollect ("ID", _ variant_t (ID ));
M_pRecordset-> PutCollect ("NameGsz", _ variant_t (Name ));
M_pRecordset-> PutCollect ("XinBie", _ variant_t (XingBie ));
M_pRecordset-> PutCollect ("ZhaoShu", _ variant_t (ZhaoShu ));
// D: UpdateDatabaseIt can also be understood as writingDatabase
M_pRecordset-> Update ();
}
Catch (_ com_error e)
{
AfxMessageBox ("addedDatabaseFailed! "); // Display the error message
}
AfxMessageBox ("addedDatabaseSucceeded ");




To be continued

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.