Connect to the database using ADO in MFC

Source: Internet
Author: User

 

Summary of Using MFC to connect to the database through ADO in VC ++ (excluding exception capturing)
Here we will mainly talk about the connection between MFC and SQL2000 databases.

1. Add this sentence to the stdafx. h header file.
# Import "C:/program files/common files/system/ADO/msado15.dll "/
No_namespace Rename ("EOF", "adoeof ")
2. Add it to the initinstance () function of the app class

: Coinitialize (null); // indicates the initialization of the COM library.

Right-click the app class name, add the virtual function exitinstance (), and add the code to it.

: Couninitialize (); // release the com library.

3. Obtain the connection string.

The simplest example is to create a new. txt file and change its suffix. udl, double-click it, select "Microsoft ole db provide fo SQL Server" on the "providers" tab, and enter the server, database, and login method information on the "Connections" tab, finally, press "OK ". After the connection is complete, open it on the WordPad. The third line of information is displayed, for example, "provider = sqloledb.1; Integrated Security = sspi; persist Security info = false; initial catalog = ruledb_data; data Source = Pye "is the connection string. Note: If the database is located on the local machine, you can enter local directly in the Select Server field. Remember to add brackets.

4. Connect to the database

Here we introduce a compiled encapsulation class: adoconn. This class encapsulates the methods for connecting to the database, adding, deleting, modifying the database, and obtaining query records. You can use it directly. The header file and CPP file content of this class will be provided at the end of this article.

To add this class to a project, copy the Class header file and CPP file to the folder where the project is located. Select project> Add to project> files in the project workspace to add these two files.

Then, you can apply this class in the program.

First, set an object of this class in the header file of the class to be used in the database, that is, add the code: adoconn m_ado; Note: Remember to add # include "adoconn. H" at the beginning ".

Before applying this object to operate on the database, initialize it: m_ado.oninitadoconn (strconnect), where strconnect is the connection string obtained above.

To obtain some record sets in the database, use m_ado.getrecordset (strsql). Use strsql to store query statements and query results in m_ado.m_precordset. Then, use getcollect () the function gets the values of each field of all matching records one by one. Use m_ado.m_precordset.close () to close the record set.

The addition, modification, and deletion operations are completed using m_ado.executesql (strsql.

In addition, if multiple record sets are required at the same time, you also need to add the record set object in the header file of the class to be used in the database, that is, _ recordsetptr m_precordset; m_precordset also needs to be initialized before use, the initialization statement is m_precordset.createinstance (_ uuidof (recordset). Similarly, you must use the close () function to close each record set after it is used up.

5. If you encounter 102 errors during database application compilation, you can delete the debug folder and re-compile it.

Adoconn Class header files:

# If! Defined (afx_adoconn_hda-2b491720_fa04_4800_b616_219e55abea461_included _)
# Define afx_adoconn_h1_2b491720_fa04_4800_b616_219e55abea461_encoded _

# If _ msc_ver> 1000
# Pragma once
# Endif // _ msc_ver> 1000

Class adoconn: Public cobject
{
Public:
// Add a pointer to the connection object:
_ Connectionptr m_pconnection;
// Add a pointer to the recordset object:
_ Recordsetptr m_precordset;
Char error [1024];
Public:
_ Connectionptr & getconnptr () {return m_pconnection ;}
_ Recordsetptr & getrecoptr () {return m_precordset ;}
Public:
// Transaction rollback
Bool rollbacktrans ();
// Submit the transaction
Bool committrans ();
// Start the transaction
Bool begintrans ();
Bool adobof (); // Header
Bool adoeof (); // tail
Bool movenext (); // next
Bool CloseTable (); // close the table
Bool closeadoconnection (); // close the connection
Bool getcollect (lpctstr name, cstring & lpdest); // obtain the value of a field
// Execute the SQL statement including update Delete Insert
Bool executesql (lpctstr lpszsql );
// Initialize the database connection
Bool oninitadoconn (lpctstr connstr );
// Execute the SELECT statement to obtain the record set
_ Recordsetptr & getrecordset (lpctstr lpszsql );
Adoconn ();
Virtual ~ Adoconn ();

};

# Endif //! Defined (afx_adoconn_hda-2b491720_fa04_4800_b616_219e55abea461_included _)

Class cadoexception: Public cexception
{
Public:
// Constructor
Cadoexception (char * pchmessage );
 
Public:
~ Cadoexception (){}
Cstring m_strmessage;
Virtual bool geterrormessage (lptstr lpstrerror, uint nmaxerror,
Puint pnhelpcontext = NULL );
PRIVATE:
Int m_nerror;
 
};

CPP file of the adoconn class:

# Include "stdafx. H"
# Include "adoconn. H"

# Ifdef _ debug
# UNDEF this_file
Static char this_file [] =__ file __;
# Define new debug_new
# Endif

//////////////////////////////////////// //////////////////////////////
// Construction/destruction
//////////////////////////////////////// //////////////////////////////

Adoconn: adoconn ()
{
Memset (error, 0,1024 );
 
}

Adoconn ::~ Adoconn ()
{

}

//////////////////////////////////////// //////////////////////////////
// Cadoexception class
//////////////////////////////////////// //////////////////////////////

//////////////////////////////////////// //////////////////////////////
// Construction/destruction
//////////////////////////////////////// //////////////////////////////

Cadoexception: cadoexception (char * pchmessage)
{
M_strmessage = pchmessage;
M_nerror = getlasterror ();
}
Bool cadoexception: geterrormessage (lptstr lpstrerror, uint nmaxerror, puint pnhelpcontext/* = NULL */)
{
 
Char text [200];
If (m_nerror = 0)
{
Wsprintf (text, "% s error", (const char *) m_strmessage );
}
Else
{
Wsprintf (text, "% s Error # % d", (const char *) m_strmessage, m_nerror );
}
Strncpy (lpstrerror, text, nmaxerror-1 );
Return true;
}

Bool adoconn: oninitadoconn (lpctstr connstr)
{
: Coinitialize (null );
 
Try
{
// Create a connection object
M_pconnection.createinstance ("ADODB. Connection ");
// Set the connection string, which must be of the BSTR or _ bstr_t type
_ Bstr_t strconnect = _ bstr_t (connstr); // "provider = sqloledb; server = 127.0.0.1; database = eventlogg; uid = event; Pwd = event ;";
M_pconnection-> open (strconnect, "", "", admodeunknown );
Return true;
}
// Catch exceptions
Catch (_ com_error E)
{
// Display the error message
Trace (E. Description ());
// Sprintf (error, "connection to the database failed please check connection string/R/n current connection string: % s", connstr );
// Throw new cadoexception (error );
Throw new cadoexception ("database connection failed ");
}
 
}

// Execute the SQL statement including update Delete Insert
Bool adoconn: executesql (lpctstr lpszsql)
{
// _ Variant_t recordsaffected;
Try
{
// Execute method of the connection object :( _ bstr_t commandtext,
// Variant * recordsaffected, long options)
// Commandtext is a command string, usually an SQL command.
// The recordsaffected parameter indicates the number of rows affected by the operation,
// The options parameter indicates the commandtext type: adcmdtext-text command; adcmdtable-Table Name
// Adw.proc-stored procedure; adcmdunknown-Unknown
M_pconnection-> execute (_ bstr_t (lpszsql), null, ad1_text );
Return true;
}
Catch (_ com_error E)
{
Trace (E. Description ());
// Sprintf (error, "/T failed to execute SQL statement/R/n SQL statement: % s", lpszsql );
// Throw new cadoexception (error );
Throw new cadoexception ("SQL statement execution failed ");
}
 
}
// Execute the SELECT statement to obtain the result set. The result set is placed in m_precordset.
_ Recordsetptr & adoconn: getrecordset (lpctstr lpszsql)
{
Try
{
// Create a record set object
M_precordset.createinstance (_ uuidof (recordset ));
// Obtain records in the table
M_precordset-> open (_ bstr_t (lpszsql), m_pconnection.getinterfaceptr (), adopendynamic, adlockoptimistic, adshorttext );
}
// Catch exceptions
Catch (_ com_error E)
{
// Display the error message
Trace (E. Description ());
// Sprintf (error, "/T failed to execute the SELECT statement/R/nselect statement: % s", lpszsql );
// Throw new cadoexception (error );
Throw new cadoexception ("failed to execute the SELECT statement ");
}
// Return record set
Return m_precordset;
}

// Obtain the value of a field
Bool adoconn: getcollect (lpctstr name, cstring & lpdest)
{
Variant VT;
Try
{
Vt = m_precordset-> getcollect (name );
/* _ Bstr_t BSTR = (_ bstr_t) vt;
If (lpdest! = "")
{
Strcpy (lpdest, BSTR );
}*/
If (vt. VT! = Vt_null)
Lpdest = (lpcstr) _ bstr_t (VT );
Else
Lpdest = "";

}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, "failed to get field: % s value", name );
Throw new cadoexception (error );
}
Return true;
}
// Close the database
Bool adoconn: closeadoconnection ()
{
Try
{
M_pconnection-> close ();
}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, E. Description ());
Throw new cadoexception ("failed to close the Database ");
}
Return true;
}
// Close the table
Bool adoconn: CloseTable ()
{
Try
{
M_precordset-> close ();
}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, E. Description ());
Throw new cadoexception ("failed to close the table ");
}
Return true;
}
// Next
Bool adoconn: movenext ()
{
Try
{
M_precordset-> movenext ();
}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, E. Description ());
Throw new cadoexception ("moving the result set to the next failed ");
}
Return true;
}
// End
Bool adoconn: adoeof ()
{
Return m_precordset-> adoeof;
}
// Header
Bool adoconn: adobof ()
{
Return m_precordset-> BOF;
}
// Start the transaction
Bool adoconn: begintrans ()
{
Try
{
M_pconnection-> begintrans ();
}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, E. Description ());
Throw new cadoexception ("transaction start failed ");
}
Return true;
}
// Submit the transaction
Bool adoconn: committrans ()
{
Try
{
M_pconnection-> committrans ();
}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, E. Description ());
Throw new cadoexception ("failed to submit transaction ");
}
Return true;
}
// Transaction rollback
Bool adoconn: rollbacktrans ()
{
Try
{
M_pconnection-> rollbacktrans ();
}
Catch (_ com_error E)
{
Trace (E. Description ());
Sprintf (error, E. Description ());
Throw new cadoexception ("failed to roll back the transaction ");
}
Return true;
}

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.