MFC database connection with Ado

Recently seen a lot of MFC at the forum ADO database connectivity issues mistakes, I also encountered this situation, study the fundamental reason is because we have some initialization code in reference to the program or process is not clear example of this is I find a full example, include instructions to initialize the database, I had no problem with the test, for your reference!

 

VC ++ using MFC method of connecting to the database through ADO summary (not including the exception capture)

Here mainly about the connection of MFC and SQL2000 database.

1. This sentence is added in the header file StdAfx.h

#import "c:\program files\common files\system\ado\msado15.dll"\

 no_namespace rename("EOF","adoEOF")

2. () function was added in InitInstance App class

:: CoInitialize (NULL); // initialize com library represents

Right click the Add App class virtual function name ExitInstance (), the code added thereto

 :: CoUninitialize (); // release com library.

3. Obtain the connection string.

     The easiest way is to create a .txt file, its name suffix .udl, double-click it, select "Microsoft OLE DB Provide fo Sql Server" in the "Provider" tab, then "Connect" tab select fill in the information server, database, landing approach, and finally click "OK." After the connection is completed, the tablet which was open, the third line information, such as the "Provider = SQLOLEDB.1; Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = RuleDB_Data; Data Source = PYE" is the Connection String . Note that if the database is located in the unit, select the server to fill a column can be filled directly (local), remember to add brackets.

4. Connect the database

     In the preparation of a good package incorporated herein categories: ADOConn. This class encapsulates connected database, the database to add, delete, and modify operations query log acquisition method set operation. Users can be used directly, cpp file header and the contents of this class is given herein.

    Method of adding the class in a project where is: copy the class header file and cpp file to the folder where the project is located. Then select the workspace project Project-> Add to Project-> Files, choose to join these two files.

     After that, you can use this class in the program.

    First, set up a database to use in the class of the class header in the object, that is added to the code: ADOConn m_Ado; Note: Remember to first at the top to join #include "ADOConn.h".

    Application of the object before operation of the database, first initializes: m_Ado.OnInitADOConn (strConnect); wherein strConnect acquired is the connection string above.

    To obtain part of the record set in the database, with m_Ado.GetRecordSet (strSql); wherein strSql stored query, the query result is stored in m_Ado.m_pRecordset then available GetCollect () function one by one to obtain the fields of all the matching records value. I remember after use with m_Ado.m_pRecordset.Close () off the record set.

   Add, modify, delete, all with m_Ado.ExecuteSQL (strSql); statement completion.

   In addition, if at the same time need to set multiple records, you also need to use in the class header file in a database record set object is added, that _RecordsetPtr m_pRecordset; m_pRecordset also need to initialize before using initialization statement: m_pRecordset.CreateInstance (__uuidof (Recordset)) ;, the same, each time after recording current runs have to use a Close () Close.

5. If you encounter 102 errors in the database when the application is compiled, you can delete the Debug folder recompiling.

ADOConn class header file:

#if !defined(AFX_ADOCONN_H__2B491720_FA04_4800_B616_219E55ABEA46__INCLUDED_)

#define AFX_ADOCONN_H__2B491720_FA04_4800_B616_219E55ABEA46__INCLUDED_

#if _MSC_VER > 1000

#pragma once

#endif // _MSC_VER > 1000

class ADOConn : public CObject 

{

public:

 // add a link to Connection object pointer:

 _ConnectionPtr m_pConnection;

 // add a point Recordset object pointer:

 _RecordsetPtr m_pRecordset;

 char error[1024];

public:

 _ConnectionPtr& GetConnPtr()    {return m_pConnection;}

 _RecordsetPtr& GetRecoPtr()     {return m_pRecordset;}

public:

 // transaction rollback

 BOOL RollbackTrans();

 // submit Affairs

 BOOL CommitTrans();

 // transaction begins

 BOOL BeginTrans();

 BOOL adoBOF (); // head

 BOOL adoEOF (); // End

 BOOL MoveNext (); // next

 BOOL CloseTable (); // Close the table

 BOOL CloseADOConnection (); // close the connection

 BOOL GetCollect (LPCTSTR Name, CString & lpDest); // get the value of a field

 // execute a SQL statement update delete insert

 BOOL ExecuteSQL(LPCTSTR lpszSQL);

 // initialize the database connection

 BOOL OnInitADOConn(LPCTSTR ConnStr);

 // execute select statement to get the record set 

 _RecordsetPtr& GetRecordSet(LPCTSTR lpszSQL);

 ADOConn();

 virtual ~ADOConn();

};

 

#endif // !defined(AFX_ADOCONN_H__2B491720_FA04_4800_B616_219E55ABEA46__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;

 

};

 

======================

ADOConn class cpp file:

#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, must be BSTR type or types _bstr_t

  _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 an error message

  TRACE(e.Description());

// sprintf (error, "establishing a database connection Check connection string \ r \ n this connection string:% s", ConnStr);

//  throw new CADOException(error);

  throw new CADOException ( "Database connection failed");

 }

 

}

 

// execute a SQL statement update delete insert

BOOL ADOConn::ExecuteSQL(LPCTSTR lpszSQL)

{

 // _variant_t RecordsAffected;

 try

 {

  // Connection object's Execute method: (_ bstr_t CommandText, 

  // VARIANT * RecordsAffected, long Options ) 

  // where CommandText is a command string, usually SQL command.

  // RecordsAffected parameter is the number of rows affected after the operation is completed, 

  // Options parameter indicates the type of CommandText: adCmdText- text commands; adCmdTable- table

  // adCmdProc- stored procedures; adCmdUnknown- unknown

  m_pConnection->Execute(_bstr_t(lpszSQL),NULL,adCmdText);

  return true;

 }

 catch (_com_error e)

 {

  TRACE(e.Description());

// sprintf (error, "\ t execute SQL statement failed \ r \ n SQL statement:% s", lpszSQL);

//  throw new CADOException(error);

  throw new CADOException ( "Execute SQL statement failed");

 }

 

}

// execute SELECT statements, result sets, the result set is placed in m_pRecordset

_RecordsetPtr& ADOConn::GetRecordSet(LPCTSTR lpszSQL)

{

 try

 {

  // Create a record set object

  m_pRecordset.CreateInstance(__uuidof(Recordset));

  // Get a record in the table

  m_pRecordset->Open(_bstr_t(lpszSQL),m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);

 }

 // catch exceptions

 catch (_com_error e)

 {

  // display an error message

  TRACE(e.Description());

// sprintf (error, "\ t SELECT statement failed \ r \ nSELECT statement:% s", lpszSQL);

//  throw new CADOException(error);

  throw new CADOException ( "execute a SELECT statement failed");

 }

 // returns record set

 return m_pRecordset;

}

 

// Get 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, "Get Field:% s value failed", 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 ( "close the database failed");

 }

 return TRUE;

}

// Off Table

BOOL ADOConn::CloseTable()

{

 try

 {

  m_pRecordset->Close();

 }

 catch (_com_error e)

 {

  TRACE(e.Description());

  sprintf(error,e.Description());

  throw new CADOException ( "Table off failure");

 }

 return TRUE;

}

//next

BOOL ADOConn::MoveNext()

{

 try

 {

  m_pRecordset->MoveNext();

 }

 catch (_com_error e)

 {

  TRACE(e.Description());

  sprintf(error,e.Description());

  throw new CADOException ( "failure results in the set toward a");

 }

 return TRUE;

}

//tail

BOOL ADOConn::adoEOF()

{

 return m_pRecordset->adoEOF;

}

//head

BOOL ADOConn::adoBOF()

{

 return m_pRecordset->BOF;

}

// transaction begins

BOOL ADOConn::BeginTrans()

{

 try

 {

  m_pConnection->BeginTrans();

 }

 catch (_com_error e) 

 {

  TRACE(e.Description());

  sprintf(error,e.Description());

  throw new CADOException ( "Transaction begin to fail");

 } 

 return TRUE;

}

// submit Affairs

BOOL ADOConn::CommitTrans()

{

 try

 {

  m_pConnection->CommitTrans();

 }

 catch (_com_error e)

 {

  TRACE(e.Description());

  sprintf(error,e.Description());

  throw new CADOException ( "submit transaction failed");

 }

 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 ( "roll back the transaction failed");

 }

 return TRUE;

}

Guess you like

Origin blog.csdn.net/xiebingsuccess/article/details/91850680