Using ADO to access Microsoft's Access database in MFC to implement additions and deletions

Source: Internet
Author: User
Tags time limit try catch access database

Disclaimer: Companies outside Baidu are free to reprint the article.


As I mentioned in my last blog post, ADO is not related to MFC, and ADO is a standalone component. So in order to use ADO, we are going to introduce ADO into MFC.


ADO is a dynamic link library named Msado15.dll, which behaves as a hard disk.


First step: Create a dialog box MFC program in VS2010.


Step Two: Add a line of code to stdafx.h (add location after # include <afxdisp.h>//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 This nothing to say is to introduce the meaning, "C:\Program files\common Files\system\ado\msado15.dll" means a full path, is Msado15.dll

The location of this file on the hard disk. If your system has not made a deliberate change, then this path should be him.


No_namespace, what does that mean? The translation is not to use the namespace is not to use ADO this component of its own namespace or you use some of the ADO interface later


You need to add something in front (plus what.) I don't know, I stopped people saying that, too.

Rename ("EOF", "endoffile") This sentence even if you rename EOF, why rename it. This is because there is the word EOF in MFC but the meaning and EOF inside ADO are not


One meaning so you need to rename it or ADO the goods will go crazy. You can name it and repeat it with the name you already have. The name is endoffile (some guys like to name Adoeof)

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Reprint Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

#import语句实际上相当于执行了API涵数LoadTypeLib (). #import语句会在工程可执行程序输出目录中产生两个文件, *.TLH (type library header file) and *.tli (type library implementation file), which produce smart pointers for each interface, and declare for various interface methods, enumeration types, CLSID, etc. Create a series of wrapper methods.

Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Turn xxxxxxxx


Okay, the second step is over, and the third step begins.



The third step is to initialize the post-use uninstall as if it were the other component libraries in the world (this is what the teacher said, who can unfold it)

How to initialize it.

xxxxxxxx Reprint Xxxxxxxxxxxxxx

In the initial process of the program need to initialize the component, generally can be used CoInitialize (NULL), to implement, this method at the end to close the initialization of COM, you can use the following statement CoUninitialize (), to implement. There is another way to implement the initialization of COM in MFC, which only requires a single statement to automatically initialize COM and close COM at the end of the operation, the statement is as follows:

AfxOleInit ()


In order for the program to be more perfect, suggest writing

if (! AfxOleInit ())//This is the initialization of COM libraries
{
AfxMessageBox ("OLE initialization error!");
return FALSE;
}


This function can be placed in the initialization function of the Theapp object: InitInstance ().

PS: If you do not know the initialization function of Theapp, please click on the x number in the upper right corner of the webpage because this article is not suitable for you

xxxxxxxx Reprint Xxxxxxxxxxxxxx


Fourth step: do so much preparation work finally can say oh that ADO.

First look at the ADO of those things I we can use.

ADO contains some top-level objects:
Connection (Connection), which represents the connection to the database
Recordset, which represents a collection of database records
command, which represents an SQL command
Records (record), representing a collection of data
Stream, which represents the sequential collection of data
Errors, which represent unexpected results in database access
Fields (field), which represents a database field
Parameter (Parameter), which represents an SQL parameter
property, saving the object's information


I usually use the top three objects. I'm not familiar with anything else.


Fifth step: Create three objects in MFC's dialog box, which is the object of the three smart pointers.

This object (can actually be called an object, I don't know what to call it.) Enter the dialog box class

The following figure is the result of my creation


Sixth step: Just now the three smart pointer objects were created by me.

Now that you've created it, you can use it. Where to use it. Now that these three objects belong to a dialog class, you can use them in the Instantiation object of the dialog class.

Note the following is the core code.

First of all, the core code of the overall idea.

A: Link Database B: Opening a Recordset is equivalent to assigning a recordset to a record set in a database. This table exists in memory.

C: Using ADO related functions to make the recordset more and more censored D: Turn off the recordset E: Break link

This is the time to complete samsara.


Seventh step: establishing and linking the database

Opening a database can also be called a linked database

Because the operation of the data is very uncertain, the operation of the database is mostly error-grabbing is the Try Catch

HRESULT hr;
Try
{
Create a connection instance first
hr = M_pconnection.createinstance (__uuidof (Connection));//Create Connection Object
if (SUCCEEDED (HR))
{
m_pconnection->connectiontimeout=600;//Link Database time limit
m_pconnection->commandtimeout=120;//may be a time limit for SQL statement execution
Then open the database the parameters of the open function are very fastidious
The Open method opens a connection to the data source. When the connection is open, you can execute commands on the data source
A string value that contains information about the connection. The string consists of a series of parameter=value statements separated by semicolons.
A string value that contains the name of the user to use when establishing the connection.
A string value that contains the password to use when establishing the connection.
A ConnectOptionEnum value that determines whether the method should be returned (synchronous) or before the connection is established (asynchronously).
hr = M_pconnection->open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=home.mdb", "" "," "", admodeunknown);//
The ConnectionString property has 5 parameters:
Provider---The name of the provider used for the connection.
The name of the file name---provider-specific files (for example, persisted data source objects) that contain pre-built connection information.
Remote provider--The name of the provider that is used when the client connection is turned on. (Remote Data Services only.) )
Remote server--The path name of the server that is used when the client connection is turned on. (Remote Data Services only.) )
The URL---Identifies 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,
Admodeshareexclusive = 12,
adModeShareDenyNone = 16,
Admoderecursive = 4194304
*/


}
}
catch (_com_error E)///catch exception
{
CString errormessage;
ErrorMessage. Format ("Connection database failed!/r/n error message:%s", E.errormessage ());
AfxMessageBox (errormessage);
}
AfxMessageBox ("Open database Successfully");


Eighth step: Create a record set


M_precordset.createinstance (__uuidof (Recordset));
Try
{
M_precordset->cursorlocation = adUseClient; Need to transfer data to the local, application example is to disconnect the database for the recordset operation, that is, in-memory operation
Instead of writing to the remote database. Conversely, there are aduseserver that operate directly in the database.
M_precordset->open ("SELECT * from Jianghu",//sql statement
M_pconnection.getinterfaceptr (),
adopendynamic,//cursor Type
adlockoptimistic,//optimistic Lock
adCmdText);//Command type
/*
When you first open a recordset, the current record pointer points to the first record, while the BOF and EOF properties are False. If there is no record, the BOF and EOF properties are True


*/
}
catch (_com_error *e)
{
AfxMessageBox (E->errormessage ());
}
M_mydatagrid.putref_datasource (M_precordset);//The function that links the object to the DataGrid control. In VC6 is Setrefdatasource
AfxMessageBox ("Open Recordset successfully");

Nineth Step: Add Rows to the table

//Database operation:  
//special need for cursor location and database primary key can not be repeated or error
//First step: Define four strings to get the data in the edit control
CString ID = "2";
CString Name = "wind Clear";
CString Xingbie = "male";
CString Zhaoshu = "Lone solitary Nine Swords";
m_cedit_id. Getwindowtexta (ID);//Gets the edit box text, recorded in the Sztext variable
m_cedit_name.getwindowtexta (Name);
M_cedit_xingbie.getwindowtexta (Xingbie);
M_cedit_zhaoshu.getwindowtexta (Zhaoshu);
 


//Second step: Just start the library operation
Try
{

//a: Select cursor position
M_precordset->movefirst ();// The newly created data is added to the last bar of the DataGrid but is the first in the database.
//b: Reminding the system I'm going to add muscle data.
M_precordset->addnew ();
C: Call function putcollect 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: Updating the database can also be understood as writing to the database
M_precordset->update ();
}
catch (_com_error e)
{
AfxMessageBox ("Increase database failure!"); Display error message
}
AfxMessageBox ("Increase database Success");




Not 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.