For beginners, when using the ADO to access the database, involving various data type conversions, there may be some difficulty, I have tried to encapsulate the ADO access database, making it more convenient to use the existing VC data type, more convenient to use ADO operation database. The following are separately provided by two encapsulated ADO database access, one is the connection class of the database, one is the class accessible by the database field.
In the connection class, you can see that there is no recordset's member variable in the connection class, because in this whole database application, the database connection is generally enough, and the reocordset that is opened at the same time may not only one. So, if two in the same class, then if you want to open two records at the same time, you need to create two instances of the class, you need to open two database connections, if you connect the same database, open Two connections means unnecessary waste of resources.
The database field access class, simplifies, obtain the operation of the database field content, avoiding the trouble of data type conversion.
Both classes have more considerations for error handling, and in the access database, if there is no error handling, the harm is obvious.
#ifndef _bbadoconnect_h # Define _bbadoconnect_h
//// ADO access to the database // class software environment: the need MSADO15.DLL // Author: Deng Zhenbo // 2001.4.20 // Email: seesi@163.com// Home: seesi.51.net
// Description: Encapsulates the operation function and ADO access database error handling // enabling the ADO access database // including: ADO connection database, open record set, execute SQL, and // transaction processing, The ADO record set Converts Common Data Types (CSTRING, CHAR, LONG, FLOAT, etc.) //// use: 1. Define a CBBADOCONNECTION instance: cbbadoconnection m_adoconn; // 2. Establish a connection: m_adoconn.open (strConnString); // If there is a needless to reconnect, the parameter BREPEN is set to TREU // 3. Open Record: //// _recordsetptr * prsthis = null; // prsthis = new _recordsetptr; // cstring strsql; // strsql = "select * from table_name"; // // If the recordset opens failed //
IF (! (m_adoconn.openrecordset) // Return False; // 4. Establish a record set value // Note need to be constructed with parameter // CbbrstValues RSV (M_adoconn, prsthis); // // 5. Value // rsv.getvaluelong (& m_NDEPTID, 1L) of the field; // gets the value of the first field // rsv.getValUStr (m_strname, "id"); // Get the value of the first field name ID // Other Similarity. If you need to get the field value of the NTEXT type in SQL Server, you can use the // GetValText (CString & Strtext, CString & StrfieldName) function //6. Record of records (* prsthis) -> MoveNext () and other similar functions // 7. Recording set does not need to release its resource // 1) Close Record Set // 2) Delete Record Set Pointer // EG (* PRSTHIS) -> Close (); // delete prsthis; // prsthis = null; / / Otherwise Will cause memory leak // // Note: // 1. The program must initialize the COM environment. Please add the AFXoleinit function initialization environment in the application class, otherwise the call of ADO will fail // 2. If you need to call the stored procedure SQL statement to change to "EXEC" stored procedure name, the same //////////////// ///> Description: You can use it casually in the program, modify this code , But please don't delete some of the file headers. If you need to reprint, please indicate the source. // msado15.dll must be placed in the directory where this document is located, or specify the following MSADO15.DLL full path // # if! defined (__ afxado_h) #import "msado15.dll" NO_NAMESPACE RENAME ("EOF", "AdoEOF") / Rename ("LockTypeenum", "ADOLOCKTYPEENUM") / Rename ("DattyPeenum", "AdoDataTypeenum" / Rename ("FieldattributeEnum",
"AdofieldttributeEnum" / rename ("EditModeenum", "AdoEditmodeenum" / Rename ("RecordStatusenum", "AdorecordStatusenum")
/ Rename ("ParameterDirectionenum",
"AdoparameterDirectionNum") # Endif //! defined (__ afxado_h)
class CBBAdoConnection {public: CBBAdoConnection (); virtual ~ CBBAdoConnection (); public: int SetConnTimeOut (long lTimeOut); // Set the connection timeout int SetCommTimeOut (long lTimeOut); // set the command execution timeout BOOL IsConnectClose (); // Analyzing Connection has opened int ExecuteSQL (LPCSTR SZSQL); // Simple execution SQL statement, does not return record set // Open database record set // parameter: // strsql record set SQL statement // RS returned record set _RecordSetptr object // SconNString database connection string // If the database connection is already opened, the parameter is useless // If the database is connected, the connection string is given, the database connection Bool OpenRecordset (CString strsql, _recordsetptr * RS , Cstring sconnstring = ""); // Open the database record set BOOL OpenRecordset (const char * ssql, _recordsetptr * rs, char * sconnstring = null); // Open database connection // parameter: // strconnstring connection string // SCONNSTRING connection string // Breopen is reopened, if false, // will first determine if the database is opened if it is not opened, // If you have already opened, no operation // If true, there is no condition turn on. Bool OpenConnection (CString Strconnstring, Bool Breopen = false); BOOL OpenConnection (Char * Sconnstring, Bool Breopen = false); void closeconnect (); // Turns the database connection
Bool ExecuteTrans (CStringArray Arrstrsql); // Transaction, does not return any record set, parameter is a transaction SQL array
_ConnectionPtr * GetConnection (); // get pointer _ConnectionPtr CString GetConnString (); // get the connection string private: enum ERRORFrom {ErrFormOpenConnsction, ErrFromOpenRecordset, ErrFormCloseConnection, ErrFormTanslation}; _ConnectionPtr * m_pConn; char m_szConnString [512]; /// Protected: Void ReportError (Int NerrorFrom);
Class CBBRSTVALUES {public: // Method // If there is no parameter structure, please call the InitConnectAndRST method // other two configurations after the configuration does not need to call the InitConnectAndRST method cbbrstvalues (); CbbrstValues (_ConnectionPtr * PConn, _RecordSetptr * PRS); CBBRSTVALUES (CBBADOCONNECTION * PBBADOCONN, _RecordSetptr *
PRS);
virtual ~ CBBRstValues (); public: // initialize the connection and as team record set object void InitConnectAndRst (_ConnectionPtr * pConn, _RecordsetPtr * pRs); void InitConnectAndRst (CBBAdoConnection * pBBAdoConn, _RecordsetPtr * Rs); // GetValText database functions // give NTEXT field value // parameter: // strText is used to receive the return value (field value) // StrfieldName field name, the field data type must be NTEXT type BOOL getValtext (CSTRING & Strtext, CString & StrfieldName); // Get database nText field Value // getValUESTR function // Get digital, date type, and character field value function // parameter: // CVAL is used to receive a string pointer of the return value (field value), and require a sufficient memory unit // Or enough character arrays that are sufficient to accommodate field content. // The name or index of the VINDEX database field, the variable body, generally not directly use this parameter, // The data type of the data type that should be used with the same form can be digital, date and character type // nfieldlen needs to return the length of the string of the data, if to -1, return the entire field value // lpszfieldName field name, the data type of the database field can be digital, date type, and characters // nfieldIndIndex in SQL statement The data type of the index serial number database field of the middle field can be digital, date and character type
// getValuelong function // Get digital, date type, and character field value function // parameter: // LVAL is used to receive the return value (field value) // vindex database field name or index, variable body type, generally not directly Use this parameter, // The data type requirement of the parameter call // database field should be used in the same form of the data type requirement is a digital type (INT, long) // lpszfieldname field name, the data type of the database field can be digital, date Type and character // nfieldIndIndex's index serial number database field of fields in the SQL statement can be digital, date type, and characters
// getValueflaot function // Get digital, date type, and characters field value function // parameter: // fval is used to receive the return value (field value) // vindex database field name or index, variable body, generally not directly Use this parameter, // The data type requirements of the parameter call // database field should be used in the same form of the data type requirement is the data type of the type (INT, Long, Float, monetary, etc.) // lpszfieldname field name, database field data type. Can be digital type, date type, and character // nfieldIndIndEx's data type of the index serial number database field in the field in the SQL statement can be digital, date type and character type
Bool getValuestr (char * cval, _variant_t & vindex, int
Nfieldlen = -1); BOOL getValuelong (long * lval, _variant_t & vindex); Bool getValuefloat (Float * fval, _variant_t & vindex);
BOOL GetValueStr (char * cVal, long lIndex, int nFieldLen = -1); BOOL GetValueLong (long * lVal, long lIndex); BOOL GetValueFloat (float * fVal, long lIndex); BOOL GetValueStr (char * cVal, CString strIndex, int Nfieldlen = -1); getValuelong (long * lval, lpcstr lpszindex); Bool getValuefloat (Float * fval, cstring Strindex);
BOOL GetValueStr (CString & str, LPCSTR lpszFieldName, int nFieldLen = -1); BOOL GetValueStr (CString & str, UINT nFieldIndex, int nFieldLen = -1); BOOL GetValueStr (CString & str, _variant_t & vIndex, int nFieldLen = -1);
// Decision value is effective, whether it is null bool verifyvtdata (_variant_t & value); bool verifyvtdata; protected: _recordsetptr * m_prsthis; _ConnectionPtr * m_pconn; void reporterror ();
}
#ENDIF / / _BBADOCONNECT_H
CPP file
//// construction / destruction //
CBBADOCONNECTION :: Cbbadoconnection () {m_pconn = null;}
_ConnectionPtr * cbbadoconnection :: getConnection () {return m_pconn;}
CSTRING CBBADOCONNECTION :: getConnString () {return m_szconnstring;}
CBBADOCONNECTION:: ~ cbbadoconnection () {// Offer than connection CloseConnect ();}
BOOL CBBADOCONNECTION :: OpenConnection (Char * sconnstring, Bool Breopen / * = false * /) {// Do not need to re-open if (!! = Null && ((* m_pconn) -> State! = AdStateClosed ))).
Verify (sconnstring); strcpy (m_szconnstring, sconnstring);
Try {m_pconn = new _ConnectionPtr; M_PCONN-> CreateInstance (__ uuidof (connection)); if (m_pconn == null) Return False; HRESULT HR = (* m_pconn) -> Open ((char *) sconnstring, "", "" , -1); failed (hr)) Return false; return true;} catch (_COM_ERROR) {ReportError (ErrformopenConnSction); Return False;} catch (...) {#ifDef _debug // Show corresponding Error message MessageBox (NULL, "Database connection unprocessed exception!", "Connection failed", MB_ok | MB_ICONInformation; #else MessageBox (NULL, "connection data failed, please check if the network and database settings are correct," "" connection failed ", MB_OK | MB_ICONINFORMATION); #endif return FALSE;} SetConnTimeOut (5);} BOOL CBBAdoConnection :: OpenRecordset (const char * sSQL, _RecordsetPtr * rs, char * sConnString) {// rs = new _RecordsetPtr; VERIFY (sSQL) {
IF ((m_pconn == null) || (* m_pconn) -> state == adStateclosed)) {INT N = (* m_pconn) -> state; if (sconnstring! = null) {ix (! OpenConnection (SconNString) Return False;} // Try to connect the database else {// // if (! OpenConnection) // Return False; // messagebox (null, "database connection has been disconnected, please reconnect!", "Connect connection Question ", MB_OK | MB_ICONInInformation);
Return false;} // rs = new _recordsetptr; HRESULT HR; hr = rs-> createInstance (__ uuidof (recordset)); if (failed (hr)) {return false; // Establish an instance failed} hr = (* rs) -> Open (SSQL, M_PCONN-> GetInterfacePtr (), AdopenStatic, AdlockBatchOptimistic, -1); if (Failed (HR)) {Return False; // Open Connection Failed} Return True; // Successful Return} catch (_COM_ERROR) {// afXMESSAGEBOX (CE-> Description (); RETURN FALSE;} catch false;} catch (...) {MessageBox (Null, "Database record open failed!", "Record Fail", MB_OK | MB_ICONInInformation) Return false;} return true;} void cbadoconnection :: closeconnect () {try {if (m_pconn! = Null) {if ((* m_pconn) -> state! = Adstateclosed) (* m_pconn) -> close (); DELETE M_PCONN; M_PCONN = NULL;}} Catch (_COM_ERROR) {ReportError (ErrformCloseConnection);} catch (...) {AFXMessageBox ("Close Database connection unknown error!");}}
BOOL CBBAdoConnection :: OpenConnection (CString strConnString, BOOL bReOpen) {char c [512]; strcpy (c, strConnString.GetBuffer (0)); strConnString.ReleaseBuffer (); return OpenConnection (c, bReOpen);}
BOOL CBBAdoConnection :: OpenRecordset (CString strSQL, _RecordsetPtr * rs, CString sConnString) {char c [1024]; strcpy (c, strSQL.GetBuffer (0)); strSQL.ReleaseBuffer (); return OpenRecordset (c, rs, (char *) (LPCTSTR) sconnstring);
Bool Cbbadoconnection :: ExecuteTrans (CStringArray Arrsql) // Start transaction processing, does not return any record set, parameter is transaction SQL array {(* m_pconn) -> begintrans ();
try {_RecordsetPtr * prsThis; for (int i = 0; i
/ / Return to whether it is in the connection status BOOL CBBADOCONNECONNECTION :: IsconnectClose () {
Return (m_pconn == null) || (* m_pconn) -> state == adstateclosed);}
// Setting the connection timeout int CBBADOCONNECTION:: SETCONNTIMEOUT (LONG LTIMEOUT) {Return (* m_pconn) -> PUT_CONNECTIONTIMEOUT (LTIMEOUT);}
INT CBBADOCONNECTION :: setcommtimeout (long LTIMEOUT) {RETURN (* m_pconn) -> put_commandtimeout (LTIMEOUT);
// Report Error Void Cbbadoconnection :: ReportError (INT NerrorFrom) {copy errformopenconnsction: #ifdef _debug // Display the corresponding error message TRY {for (long L = 0; l <(* m_pconn) -> ErrorS-> Count; L ) {Errorptr PERR; Perr = (* m_pconn) -> Errors-> GetItem (L); CString Str; Str = (Char *) Perr-> description; MessageBox (Null, Str, " Connection failed ", MB_OK | MB_ICONITION);}} catch (...) {MessageBox (NULL," database connection unknown error, unable to capture specific error messages! "," Error ", MB_ICONInformation;} #else MessageBox (null, "Connection data failed, please check if the network and database settings are correct", "Connection failed", MB_ok | MB_ICONInformation); #ENDIF BREAK; Case ErrFromopenRecordset: #ifdef _debug try {for (long i = 0; i <(* m_pconn) -> Errors-> count; i ) {Errorptr Perr; perr = (* m_pconn) -> Errors-> GetItem (i); afxMessageBox;}} catch (...) {MessageBox (null, "Database connection unknown error, unable to capture specific error messages!" MB_ok | MB_ICONITION; #ENDIF BRE AK; Case ErrformCloseConnection: #ifdef _debug // Displays the corresponding error message when debugging Try {for (LONG L = 0; l <(* m_pconn) -> Errors-> count; l ) {ErrorPtr Perr; perr = (* m_pconn ) -> Errors-> GetItem (L); CString Str; str = (char *) Perr-> description; MessageBox (NULL, STR, "Connection failed", MB_OK | MB_ICONITIONFORMATION;}} catch (...) { MessageBox (NULL, "database connection unknown error, unable to capture specific error messages!", "Error", MB_ICONInInformation;
#ELSE; // MessageBox (NULL, "Close Database Connection Exception", "Close Abnormality", MB_OK | MB_ICONInformation; #ENDIF BREAK; CASE ErrformTanslation: #if Def _debug try {for (long i = 0; i <(* m_pconn) -> errors-> count; i ) {ErrorPtr Perr; perr = (* m_pconn) -> Errors-> GetItem (i); afxMessageBox;}} catch (...) {MessageBox NULL, "Database connection unknown error, unable to capture specific error messages!", "Error", MB_ICONInformation);} #else MessageBox (NULL, "Database execution task failed, please check the database.", "Task Fail", MB_ok | ); #Ndif break; default: Break;}} /// CRecordSetValus
CBBRSTVALUES :: cbbrstvalues () {;
CBBRSTVALUES :: CBBRSTVALUES (_RecordPtr * PConn, _RecordSetPtr * PRS) {Assert (PCONN); Assert (PRS); m_PrsTHIS = PRS; m_pconn = pconn;}
CBBRSTVALUES :: Cbbrstvalues (CBBADOCONNECTION * PBBADOCONN, _RECORDSETPTR * PRS) {CBBRSTVALUES (pbbadoconn-> getConnection (), PRS);
CBBRSTVALUES :: ~ cbbrstvalues () {;
Void cbbrstvalues :: INITCONNECTRST (_ConnectionPtr * PConn, _RecordSetPtr * PRS) {assert (pconn); assert (prs); m_prsthis = prs; m_pconn = pconn;}
Void CbbrstValues :: INitConnectandrst (cbbadoconnection * pbbadoconn, _recordsetptr * PRS) {INTCONNECTRST (Pbbadoconn-> getConnection (), PRS);
Bool cbrstvalues :: getValuelong (long * lval, _variant_t & vindex) {_variant_t value; try {
IF ((* m_prsthis) == null || (* m_prsthis) -> State == adstateclosed) {
#ifdef _debug afxMessageBox ("Record Collection Open!"); # else MessageBox (NULL, "Unable to read database information, possible database connection has been disconnected, please reconnect, then try again.", "Connect Questions, MB_ICONITIONMATION ); # endif returse;}
IF ((* m_prsthis) -> adoEOf) {lval = 0; return false;}
Value = (* m_prsthis) -> getCollect (vindex);} catch (_COM_ERROR) {reporterror (); return false;} catch (...) {AFXMessageBox ("Database field access unknown error! Please check if the database is changed." , MB_ICONICONFORMATION; RETURN FALSE;} IF (VerifyVTData (Value)) {* LVAL = long (value);} else {* lval = 0;}
Return True;}
Bool CBBRSTVALUES :: getValuestr (char * cval, _variant_t & vindex, int nfieldlen) {char * c = null; _variant_t value; date dt; cstring str; coledatetime da; // check is array // verify (Sizeof (CVAL) <1 ); MEMSET (CVAL, 0, SIZEOF (CVAL)); Try {IF ((* m_PRSTHIS) == Null || (* m_prsthis) -> State == AdStateclosed) {#ifdef _debug AFXMESSAGEBOX ("Recording Collection is not open! "); # else MessageBox (NULL," Unable to read database data, maybe the database connection has been disconnected, please reconnect, then try again. "," Connect Questions ", MB_ICONITION;}
IF ((* m_prsthis) -> adoeof) {CVAL [0] = '/ 0'; return false;} value = (* m_prsthis) -> getCollect (vindex);} catch (_COM_ERROR) {reporterror (); // AFXMessageBox ("Database Field Access Errors!"); Return False;} catch (...) {AFXMessageBox ("Database field access unknown error! Please check if the database is changed.", MB_ICONInInformation); return false;} if (VerifyVTData) Value)) {Switch (Value.vt) {CASE VT_BSTR: C = (Char *) _ COM_UTIL :: ConvertBSTRTRTSTRING (V_BSTR (& Value)); if (VerifyVtdata (C)) {IF (Nfieldlen <= 0) {STRCPY (CVAL) (char *) c);} else {strncpy (cval, (char *) c, nfieldlen;}} delete c; c = null; break; case vt_i4: case vt_decimal: case vt_ui4: case vt_i8: Case Vt_ui8: Case vt_int: long; lval = long (value); LTOA (LVAL, CVAL, 10); BREAK; CASE VT_DATE: DT = Value.Date; da = COLEDATETIME (DT); // str = da.Format ("% Y-% M-% D% h:% M:% S"); str = da.format ("% y-% M-% D"); c = new char [64]; MEMSET (C , 0, SizeOf (char) * 64); STRCPY (C, Str.getBuffer (0)); str.releaseBuffer (); if (verifyvtdata (c)) {if (nfieldlen <= 0) {struct (CVAL, (char *) c);} else {strncpy CVAL, (char *) c, nfieldlen; cval [nfieldlen] = '/ 0';}} delete C; c = null; break; default: #ifdef _debug AFXMESAGEBOX ("Unpredited field data type, please handle it! "); # Else Break; #ndif break;}} else {cval [0] = '/ 0';} return true;
Bool CBBRSTVALUES :: getValuelong (long * lval, long lindex) {_variant_t vindex (lindex); Return getValuelong (LVAL, VINDEX);
BOOL CBBRstValues :: GetValueLong (long * lVal, LPCSTR lpszIndex) {_variant_t vIndex (lpszIndex); return GetValueLong (lVal, vIndex);} BOOL CBBRstValues :: VerifyVTData (char * pData) {if (pData == NULL) {return FALSE Return True;}
Bool cbrstvalues :: verifyvtdata {if (value.vt == vt_null) {return false;} return true;
Bool CBBRSTVALUES :: GetValuestr (CString & Str, LPCSTR LPSZFIELDNAME, INT NFIELDLEN / * = - 1 * /) {_variant_t vindex (lpszfieldname); Return GetValUStr (Str, VINDEX, NFIELDLEN);}
Bool CBBRSTVALUES :: GetValuestr (CString & Str, Uint NfieldIndIndIndex, int nfieldlen / * = - 1 * /) {_variant_t vindex ((long) nfieldIndex; Return getValUStr (Str, VINDEX, NFIELDLEN);}
BOOL CBBRstValues :: GetValueStr (CString & str, _variant_t & vIndex, int nFieldLen / * = - 1 * /) {TCHAR buffer [1024]; if (nFieldLen> 1023) nFieldLen = 1023; BOOL bResult = GetValueStr ((char *) buffer, VINDEX, NFIELDLEN; str.format (buffer); str.trimright (); return bresult;}
BOOL CBBRstValues :: GetValueFloat (float * fVal, _variant_t & vIndex) {_variant_t value; try {if ((* m_prsThis) == NULL || (* m_prsThis) -> State == adStateClosed) {#ifdef _DEBUG AfxMessageBox ( "Record Set Not open! "); # Else MessageBox (NULL," Unable to read database information, possible database connection has been disconnected, please reconnect, then try again. "," Connect Questions, MB_ICONITION;} IF ((* m_prsthis) -> adoEOf) {fval = 0; Return False;
Value = (* m_prsthis) -> getCollect (vindex);} catch (_COM_ERROR) {reporterror (); return false;} catch (...) {afxMessageBox ("Database field access unknown error! Please check if the connection database structure has been Change. ", MB_ICONInformation; Return False;
IF (VerifyVtdata (Value)) {* fval = float (value);} else {* fval = 0;} return true;
Bool cbrstvalues :: getValuefloat (float * fval, long lindex) {_variant_t vindex (lindex); return getValuefloat (fval, vindex);
Bool Cbbrstvalues :: getValuefloat (float * fval, cstring strindex) {_variant_t vindex (StrInDex); Return getValuefloat (fval, vindex);
Bool CBBRSTVALUES :: GetValuestr (Char * Cval, Long Lindex, Int nfieldlen) {_variant_t vindex; vindex = _variant_t (lindex); Return getValuestr (CVAL, VINDEX);
Bool CBBRSTVALUES :: getValuestr (char * cval, cstring strinderx, int nfieldlen) {_variant_t vindex; vindex = _variant_t (strindex); Return getValuestr (CVAL, VINDEX);
Void cbrstvalues :: reperterror () {# ifdef _debug try {for (long L = 0; l <(* m_pconn) -> errors-> count; l ) {Errorptr Perr; perr = (* m_pconn) -> Errors-> GetItem (L); AFXMessageBox;}} catch (...) {AFXMessageBox ("field error object access error, please check if the writing is correct.");} #} #} #} #} #} #} #} #} #} #} #} #} #} #} #} #} #} #} #} #} # }El If an error occurs, please confirm that the database structure has no change. "
BOOL CBBRstValues :: GetValText (CString & strText, CString & strFieldName) {_bstr_t varChunk; _bstr_t varNotes; long lngTotalsize, lngOffSet = 0, lngChunkSize = 100; _variant_t vFieldName = _variant_t (strFieldName); lngTotalsize = (* m_prsThis) -> Fields-> Item [vfieldname] -> actualsize / 2; if (lngtotalsize <= 0) Return False;
try {while (lngOffSet
#ifdef _debug afxMessageBox ("Get the Text Field Unknown Error"); # Endif Return False;} Return True;}
// The above code, there is no perfect place, more complete code, will be published in the future, now I have made a DLL, and some sample files, you need DLL and sample files, please contact me. . Email: seei@163.com
More Articles in My Person Home: SEESI.51.NET