How should VC ++ programmers read ADO documents

xiaoxiao2021-03-06  41

The VC programmer should read the ADO document VC programmers should read the contents of the ADO API with VB's syntax using the ADO document "ADO API Reference". But ADO programmers use different programming languages, such as VB, VC , VJ . This "ADO for VC syntax index" provides a detailed description of the VC syntax specification, including features, parameters, exception handling, and more. ADO is implemented based on several COM excuses, so its use is simpler for a programmer who is programming for COM. For example, almost all details that use COM are hidden for VB programmers, but they should pay special attention to VC programmers. The following is an overview of C and C programmers using ADO and #Import indicator, mainly describing the data type (Variant, BSTR, And SafearRay), and abnormal processing (_ROM_ERROR). Use the #import to compile the indicator #import Compilation indicator to simplify the method of using the ADO. This indicator requires a type library file name, such as ado.dll (msado15.dll), and generates a corresponding header file, including the defined type, the intelligent pointer, constant of the interface. And all interfaces are encapsulated. There is a declaration to ensure that it can directly call it (or the source form of operation), and another declaration to invoke this source and failure Throw a COM error. If the operation is an attribute, the compilation indicator can create an interactive similar VB based syntax form for this operation. Returns the operation of / set the property with the corresponding form-GetProperty / PutProperty, which sets a pointer type attribute value to an ADO object, is PutreFproperty. You will use the following form to read and write the value of the property: variable = ObjectPtr-> getProperty (); // read the value of the attribute ObjectPtr-> PutProperty (value); // Setting the value of the property ObjectPtr-> PutRefProperty; & value; / / Set the value of a pointer type attribute directly using the attribute __Declspec (Property ...) Compilation indicator is a Microsoft definition to extension to the C language, so that a function is used like a property. This way you can use the following grammatical form like reading and writing a property like using VB: ObjectPtr-> Property = value; // Set the value of the value variable = Objectptr-> Property; // Read the value of the attribute __Declspec (Property ...) Compilation indicator can only be used for the read and write function of the attribute, and the corresponding call form is automatically generated according to the attribute. Each attribute may have three functions of getProperty, PutProperty, PutRefProperty, but this compiler can only generate two interactive forms. For example, the ActiveConnection property of the Command object has two read and write functions for getActiveConnection and PutRefactiveConnection. The form of Putref is a good choice in practice, you can save the pointer of an active Connection object in this property. On the other hand, the Recordset object has a get-, put-, and putreFactiveConnection operation, but there is no syntax form that can be interactive.

Collectes, GetItem methods, and Item properties ADO define several collection Collection, including Fields, Parameters, Properties, and Errors. In Visual C , the GetItem (Index) method returns a member in Collection. Index is a variant type parameter, which can be a number of orders corresponding to the member, or a string including its name. __DECLSPEC (Property ...) Compile Indicator Generates a direct usage of the GetItem () method to the ITEM () method (the interactive syntax form mentioned above). This form is similar to the syntax form of [] when citing array element: CollectionPtr-> GetItem (index); collectptr-> item [index]; The Recordset object is booked in the Authors table in the Pubs database. Use the item () attribute to access the third field in the Fields collection of this Recordset (the collection is always numbered from 0, assuming the third field name is au_fname). Then call the value () method to assign a string value for this field. Visual Basic's grammatical form: rs.fields.Item (2) .value = "value" rs.fields.item ("au_fname"). Value = "value" or: rs (2) = "value" rs! Au_fname = "Value" Visual C grammatical form: rs-> fields-> GetItem (2) -> PUTVALUE ("Value"); RS-> Fields-> GetItem ("au_fname") -> PutValue ("Value"); or : Rs-> Fields-> item [2] -> value = "value"; rs-> fields-> item ["au_fname"] -> value = "value"; COM-specific data type, you are " The data type seen in the ADO API REFERENCE can also find the corresponding type in VC . These include standard data types, such as the Unsigned Char corresponding to the vb's Byte, Short corresponding to Integer, LONG corresponds to long. See "Syntax Indexes" will get more details on the required number of operands. As an exception's data types that use the COM use: Variant, BSTR, And Safearray. Variant Variant is a structured data type that includes a representation of a member value and its data type. Variant can represent a considerable amount of data type, even another Variant, BSTR, Boolean, IDispatch, or iunknown pointer, currency, date, etc. At the same time, COM also provides a number of methods to make conversions between data types easier. _variant_t package and manage the data type of Variant. When a method or attribute is said in "ADO API Reference", it is often meant to need a parameter of the _variant_t type. This guidelines have been understood in the parameters of "ADO API Reference".

As an exception, sometimes the operand is required to be a standard data type, such as long or byte, or an enumeration value. Another exception is that the required operand is a string String. BSTR BSTR (Basic String) is also a structured data type, including the length of string and string. COM provides a method for string spatial allocation, operation, and release. _BSTR_T package and manages this data type of BSTR. When a method or attribute is used in "ADO API Reference" to use a string parameter, a class_BSTR_T type parameter is often required. _variant_t and _BSTR_T Class Force Type Conversion typically do not need explicit type conversion code when sending a _variant_t or _bstr_t parameter to an operation. If the _variant_t or _bstr_t class provides a constructor corresponding to the parameter type, the compiler will automatically generate the appropriate _variant_t or _bstr_t value. However, when the parameter is coupled, when a plurality of construct functions are corresponding, you must explicitly call the correct constructor to get the correct parameters. For example, the function declaration Recordset :: Open method is as follows: HRESULT Open (const _variant_t & Source, const _variant_t & ActiveConnection, enum CursorTypeEnum CursorType, enum LockTypeEnum LockType, long Options); where the parameters for a variant_t ActiveConnection is a reference type variable, it Can be a connection string or a pointer to the open Connection object. The correct _variant_t type parameter will be constructed, no matter where you passed a similar "DSN = PUBS; UID = SA; PWD =;" such a string, or a pointer similar to "iDispatch *) PCONN. Or you can also explicitly write "_VARIANT_T ((iDispatch *) PCONN, TRUE)" "This code is passed to pass a _variant_t variable that contains pointers. The mandatory type conversion here (iDispatch *) avoids the ambient two identity of the IUNKNOWN interface constructor. Although few mention, but especially important, ADO is always an IDispatch interface. Any pointers that are passed in Variant must be converted to an IDispatch interface pointer. Finally, the second logical parameter of the constructor is optional, and its default is TRUE. This parameter will determine if the constructor of the Variant is called the embeddref () method, and whether it is automatically called after completing the ADO method or attribute call _variant_t :: release () method SafeArray SafeArray is also a structured data type, An array of data elements consisting of other data types. The reason why it is called safe array is because it contains the boundary information of each dimension and limits access to array elements within the boundary. When "ADO API Reference" talks about a method or attribute to use or returns an array, it usually means a SafeArray array, not a localized C / C array. For example, the second parameter of the OpenSchema method of the Connection object requires an array consisting of a Variant value. These Variant values ​​must be passed as an element of a SafeArray array. And this SafeArray array itself is passed as a variant.

Further, the first parameter of the Find method is a Variant of a one-dimensional SafeArray array; an optional first and second parameters of the AddNew method are also a one-dimensional SafeArray array; the return value of the getRows method is one Contains Variant in a two-dimensional Safearray array. The default parameter VB allows certain parameters of the omission. For example, the OPEN method of the Recordset object has five parameters, but you can skip the intermediate parameters and omitted the parameters after it. The omitted parameters are automatically created BSTR or Variant defaults. In C / C , all operands must be clear. If you want to define a string type default parameter, then define a _BSTR_T that contains an empty string. If you want to define a Variant type default parameter, then define a value of DISP_E_PARAMNOTFOUND, the type of VT_ERROR _VARIANT_T. You can also use the equivalent of the equivalent VTMissing with the #import compilation indicator. VtMissing has three accident situations: Connection and Command object's EXECUTE method, RecordSet object's nextRecordset method. _RecordsetPtr Execute (_bstr_t CommandText, VARIANT * RecordsAffected, long Options); // Connection _RecordsetPtr Execute (VARIANT * RecordsAffected, VARIANT * Parameters, long Options); // Command _RecordsetPtr NextRecordset (VARIANT * RecordsAffected); // Recordset the parameters Parameters RecordsAffected Both point to the pointer of Variant. Parameters is an incoming parameter that points to a Variant's address that contains one or set of parameter information, which will determine the content executed by the command. Recordsaffected is an outgoing parameter that pointing to a Variant's address that contains the number of rows when it is returned. In the Execute method of the Command object, if only no parameters are not parameters, you need to set parameters to & VTMissing (recommended) or an empty pointer (NULL). If it is passed an empty pointer, the equivalent VTMissing will be delivered and completed. In all methods, the number of records that do not need to return the affected records can be indicated by setting the RecordSaffected to an empty pointer. At this time, this null pointer actually becomes an indicator indicating that the method is abandoned by the number of records. Therefore, the following coding is effective: pConnection-> EXECUTE ("CommandText", NULL, AdcmdText); pcommand-> execute (null, null, adcmdtext); PrecordSet-> NextRecordset (NULL); error processed in COM, Most of the operation always returns a hResult value to indicate whether the function is successfully completed. Compilation indicator #import provides a packaged code for all source methods and properties and checks the returned HRESULT value. If the HRESULT indication fails, these packaged code will throw a COM error by calling the _Com_issue_ERROREX () to HRESULT as the parameter. The COM error object will be captured in the Try-Catch block (for efficiency considerations, actually captured a reference pointer for a _com_error object). Remember, the error generated by the ADO operation failed is an ADO error. The error returned by the next layer provides an error object in the ERRORS collection in the Connection object.

Compilation indicator #import can only provide error handling routines for methods and properties declared in Ado.dll. Therefore, you can write your own error check macros or built-in functions based on the same error handling mechanism. See "Visual C Extensions" and subsequent sample code this article. The agreement when encoding in VC and VB is an overview of how to write code for how to write code using VB and VC in the ADO document. Declare an ADO object in VB, an ADO object variable (here, the Recordset object is an example) declare: DIM RST as adodb.recordset clause "AdoDb.Recordset" is the ProgID of the Recordset object registered in the registry. And the example of a Record object is declared: DIM RST AS New AdoDB.Recordset or: DIM RST AS AdoDB.Recordset Set RST = New AdoDb.Recordset, in VC , # import generates a smart pointer type for all ADO objects. For example, a data type of a pointer variable pointing to the _Recordset object is _RecordSetptr, and declares as follows: _RecordSetPtr RS; and an instance of a _recordset object is declared as follows: _RecordSetPtr rs ("adoDb.recordset"); or: _RecordSetptr rs; rs; .CreateInstance ("AdoDb.Recordset"); or: _RecordSetPtr Rs; rs.createInstance (__ uuidof (_Recordset))); When the CreateInstance method is successfully called, the variable can be used so use: rs-> open (...); Note that if the variable is an instance of a class, use "." Operator, if a pointer to an instance should use the "->" operator. A variable can be used in two ways. Because the "->" operator is overloaded, an object instance is allowed to be used like an interface pointer; "->" operator returns the pointer; the pointer returned by this returned pointer to the member of the _Recordset object. Writing the code to omit the string parameter When you need to use the VB to write the code to omit the String parameter, simply ignore this operand. But in VC , you must specify the number of operands to a _BSTR_T variable containing an empty string: _bstr_t strmissing (l "); writing the code to omit the Variant parameter When you need to use VB to write the code to omit the code of the VARIANT parameter, only It is necessary to simply ignore this operand. But in VC , you must specify all operands. The code to omit the Variant parameter simply sets the Variant to a special value, you can define a value of DISP_E_PARAMNOTFOUND, the type of VT_ERROR _VARIANT_T. It is also possible to use the equivalent of the equivalent VTMissing with the #import compilation indicator. _variant_t vtmissingyours (DISP_E_PARAMNOTFOUND, VT_ERROR); or: ... vtMissing ...; declares a variant in VB, a variant is declared as follows: DIM VARIABLENAME AS VARIANT In VC , define a _variant_t type variable. There are mainly in the following forms. Note: These statements are just a rough idea that you have used at all times.

_variant_t VariableName (value); _variant_t VariableName ((data type cast) value); _variant_t VariableName (value, VT_DATATYPE); _variant_t VariableName (interface * value, bool fAddRef = true); use Variants array in VB, using Dim statements can be Variant array programming and can use Array function. See the following example: Public Sub Arrayofvariants Dim CN As Adodb.connection Dim Rs as adoDb.recordset Dim Fld As Adodb.Field Cn.open "DSN = PUBS", "SA", "" = cn.openschema (adschemacolumns, _ array (EMPTY, EMPTY, "Authors", EMPTY)))) for each fld in rs.fields debug.print "name ="; fld.name next fld rclose cn.close end Sub's code code Demo how to pass a _variant_t Use a SafeArray array. Note Note The steps corresponding to the encoding. 1. Once again, the TESTHR () built-in function is defined to utilize the pre-stored error handling mechanism. 2. If you only need a one-dimensional array, you can use the SafeArrayCreateVector, not the SafeArrayBound declaration with the SafeArrayCreate function. The following code uses SafeArrayBound Sabound [1]; Sabound [0] .llbound = 0; Sabound [0] .CELEMENTS = 4; PSA = SafeArrayCreate (VT_VARIANT, 1, SABOUND); 3. Enumerating the mode defined by the Material ADSCHEMACOLUMNS, determines that contact Table_catalog, Table_Schema, Table_name, and Column_name quarter. To this end, a array with four Variant elements is created. The value corresponding to the third column Table_Name is set. Returned RECORDSET, which consists of several columns, is just a subset of all columns, and the value of each row maintains one or one. 4. People who are familiar with SafeArrays may be surprised by SafeArrayDestroy before withdrawing. In fact, in this case, SafeArrayDestroy () can cause an exception in a runtime. This is because VTCRiteria's destructor is called VariantClear () when _variant_t exceeds the range of use, thereby releasing SafeArray. Only call SafeArrayDestroy, without manual cleaning _variant_t, will cause the destructor to try to clear an invalid SafeArray pointer. If you want to call SafeArrayDestroy (), the code should be like this: Testhr (SafeArrayDestroy (PSA)); vtriteria.vt = vt_empty; vtcriteria.parray = NULL; actual more like letting _variant_t management SafeArray.

The complete code is as follows: #import "c: / program files / common files / system / ado / msado15.dll" / no_namespace rename ("eof", "endoffile") # include // Note 1 inline void testhr (HRESULT _HR) {if FAILED (_hr) _com_issue_error (_hr);} void main (void) {CoInitialize (NULL); try {_RecordsetPtr pRs ( "ADODB.Recordset"); _ConnectionPtr pCn ( "ADODB.Connection"); _variant_t vtTableName ( "authors "), VTCRITERIA; long ix [1]; SafeArray * psa = null; PCN-> Open (" DSN = PUBS; user ID = sa; pwd =; ",", ",", "", adconnectunspecified; // Note 2, Note 3 PSA = SafeArrayCreateVector (VT_VARIANT, 1, 4); if (! PSA) _COM_ISSUE_ERROR (E_OUTOFMEMORY); / / For the third element assigning table_name (index value 2). IX [0] = 2; TESTHR (SafearrayPuteElement (PSA, IX, & VTTABLENAME); // Since Variant does not have a SafeArray constructor, the data type and value of Variant is handled manually. vtriteria.vt = vt_Array | vt_variant; vtcriteria.parray = PSA; PRS = PCN-> OpenSchema (Adschemacolumns, Vtcriteria, vtMissing); long limit = PRS-> getfields () -> count; for (long x = 0; x < Limit; x ) Printf ("% d:% s / n", x 1, ((char *) PRS-> getfields () -> item [x] -> name)); // Note 4 PRS-> Close (); PCN-> Close ();} catch (_COM_ERROR & E) {Printf ("error: / n"); Printf ("CODE =% 08LX / N", E.Error ()); Printf ("Code Meaning =% s / n ", (char *) E.ErrorMessage (); Printf (" Source =% S / N ", (char *) E.Source ()); Printf (" Description =% S / N ", (char *) e.description ());} Couninitialize ();} Using the attribute's GET / PUTREF in VB, the name of the property is not verified, no matter whether it is read, assigned, or Give an reference.

Public Sub GetPutPutRef Dim rs As New ADODB.Recordset Dim cn As New ADODB.Connection Dim sz as Integer cn.Open "Provider = sqloledb; Data Source = yourserver;" & _ "Initial Catalog = pubs; User Id = sa; Password = "rs.pageSize = 10 sz = rs.pageSize rs.ActiveConnection = cn rs.open" authors ", adopenStatic '... rs.close cn.close end Sub The following is VC About GET / PUT / PUTREFPROPERTY Demo 1 . This example demonstrates two forms of the omitted string parameters: one is a constant strMissing, and the other is the compiler to automatically generate a temporary _bstr_t during the Open method. 2. Because the operand is already a pointer to iDispatch *, it is not necessary to convert the operating number of the RS-> PutRefactiveConnection (CN). #import "C: / Program Files / Common Files / System / ADO / MSADO15.DLL" / NO_NAMESPACE RENAME ("EOF", "Endoffile") #include

Void main (void) {coinitialize (null); try {_connectionptr CN ("adoDb.connection"); _RecordSetPtr rs ("adoDb.recordset"); _BSTR_T STRMISTING (L "); long Oldpgsz = 0, newpgsz = 5; // Note 1 CN-> Open ("provider = sqloledb; data source = a-TIMA10;" "INITIAL CATALOG = PUBS; user ID = sa; password =;", strmissing, "", adConnectunSpecified; oldpgsz = rs- > GetpageSize (); // -or- oldpgsz = rs-> pagesize; rs-> putpagesize (newpgsz); // -or- rs-> Pagesize = newpgsz; // Note 2 RS-> PutreFactiveConnection (CN); RS -> Open ("Authors", VTMissing, AdopenStatic, AdlockReadonly, Adcmdtable; Printf ("Original PageSize =% D, New PageSize =% D / N", Oldpgsz, RS-> getPagesize ()); rs-> close ); cn-> close ();} catch (_COM_ERROR & E) {Printf ("Description =% S / N", (char *) E.DESCRIPTION ());} :: couninitialize ();} Using GetItem (x ) And Item [x] below are demonstrations about Item () standard and interactive syntax in VB. Public Sub Gettem Dim Rs As New AdoDB.Recordset Dim Name As String Rs = RS.Open "Authors", "DSN = Pubs;", AdoPENDYNAMIC, _AMIC, _ ADLOCKBATCHOPTIMISTIC, ADTABLE NAME = RS (0) '-or- name = rs. Fields.Item (0) RS (0) = "Test" rs.Updatebatch 'RSTORE NAME RS (0) = Name Rs.Updatebatch rs.close End Sub The following is VC About ITEM Demonstration When accessing the item in the Collection, The index value 2 must be converted to a long type to ensure that the correct constructor is called. #import "C: / Program Files / Common Files / System / ADO / MSADO15.DLL" / NO_NAMESPACE RENAME ("EOF", "Endoffile") #include

Void main (void) {coinitialize (null); try {_recordsetptr rs ("adoDb.recordset"); _variant_t vtfirstname; rs-> open ("authors", "provike = sqloledb; data source = a-TIMA10;" Initial Catalog = pubs; user ID = sa; password =; ", adopenStatic, adlockoptimistic, adpmdtable); rs-> movefirst (); // Note 1. Name VTFirstName = rs-> fields-> GetItem ((long) 2) -> getValue (); // -or- vtfirstname = rs-> fields-> item [(long) 2] -> value; printf ("first name = '% s' / n", (char * ((_BSTR_T) vtfirstname); rs-> Fields-> GetItem ((long) 2) -> value = l "test"; rs-> update (vtMissing, vtmissing); // Restore the original name RS-> fields -> GetItem ((long) -> PUTVALUE (vtfirstname); // -or- rs-> fields-> GetItem ((long) 2) -> value = vtfirstname; rs-> update (vtMissing, vtmissing); RS-> Close ();} catch (_COM_ERROR & E) {Printf ("Description = '% s' / n", (char *) E.DESCRIPTION ());} :: couninitialize ();} utilization (iDispatch * ) Convert the pointer type 1 of the ADO object. Package an active Connection object in a variant, and then convert with (iDispatch *) to make sure the correct constructor is called. At the same time, the second parameter is set to default TRUE, which is still properly maintained after the reference number of the object is completed after the Recordset :: Open operation. 2. Expression (_BSTR_T) is not a type conversion, but an _variant_t operator that extracts a _bstr_t string from it. Expression (char *) is nor a type conversion, but an operator of _BSTR_T to extract a pointer to the string in _BSTR_T. The following code demonstrates some common operations of _variant_t and _bstr_t. #import "C: / Program Files / Common Files / System / ADO / MSADO15.DLL" / NO_NAMESPACE RENAME ("EOF", "Endoffile") #include

Void main (void) {Coinitialize (NULL); try {_connectionptr pconn ("adoDb.connection"); _RecordSetptr prst ("adoDb.recordset"); pconn-> open ("provider = sqloledb; data source = a-TIMA10; "" INITALOG = PUBS; user ID = sa; password =; "," ",", adconnectunspecified); // Note 1 prSt-> Open ("authors", _variant_t ((idispatch *) PConn, true), AdopenStatic, AdlockReadOnly, Adcmdtable; PRST-> MOVELAST (); // Note 2 Printf ("Last Name IS '% S% S' / N", (Char *) ((_BSTR_T) PRST-> getfields () -> GetItem ("au_fname") -> getValue ()), (char *) ((_BSTR_T) PRST-> Fields-> Item ["au_lname"] -> value)); prSt-> Close (); PCONN-> Close (); (_COM_ERROR & E) {Printf ("Description = '% s' / n", (char *) e.description ());} :: couninitialize ();} /// vc to ADO expansion /// For VC programmers, the data returned by ADO is converted into a general C data type each time, then stores the data into a class or structure is always a boring thing. What hates is that this also brings a low efficiency. As a result, ADO provides an interface to support direct return to a local C / C data type rather than Variant, and provide a series of preprocessing macros to easily use these interfaces. The result of doing this is a complex tool that can be easily used and can get good performance. A normal C / C client scene is to bind a record in a Recordset to a C / C structure or class containing the local C / C data type. If data is passed through Variant, this means writing a large number of conversion code to perform data conversion between Variant and C / C local types. The purpose of the expansion of VC to ADO is to simplify this process. How to use VC to extend the extension IadorecordbindBinding interface VC for ADO or bind the various fields to C / C variables of the RecordSet object. When the binding Recordset changes, the value of all the bound fields is also copied to the corresponding C / C variable. If necessary, the copied data will automatically perform the corresponding data type conversion. The BindtorecordSet method for the Iadorecordbinding interface is bound to the C / C variable. The AddNew method is to add a new line to the beded Recordset. The UPDATE method fills the new row or update existing row in the Recordset using the value of the C / C variable. The IadorecordBinding interface is implemented by the Recordset object, you don't need your own coding.

Binding entry VC Extensions for ADOs Imaging (MAP) between a RECORDSET object with a C / C variable. An image between a field and a corresponding variable is referred to as a binding entry. A predefined macro provides a binding entry for numbers, pitch or uncertaintime data. All bindings are encapsulated with the corresponding C / C variables, which is declared in a class that is derived from the VC extended Cadorecordbinding. This CADORECORDBINDING class is defined by the binding entry macro. Inside the ADO, all macros are mapped in an OLE DB DBBINDING structure and create an OLE DB Accessor object to manage all behavior and fields and variables between data conversions. The data defined by the OLE DB consists of the following three parts: a buffer that stores data; a status value indicates whether a field is successfully stored in a buffer, or whether the variable value is successfully stored in a field; data length. (See OLE DB Programmer Reference Chapter 6: More Information Read / Write Data) The header required to use VC to the ADO extension, you have to include this header file in your application: #include Bind Recordset Fields To bind the field to C / C variables, you need this: 1. Create a derived class of CadorecordSetBinding. 2. Define the binding entry and the corresponding C / C variables in the derived class. Be careful not to use a comma, and the semicolon is cut off macro. Each macro automatically defines the appropriate separator. Define a binding entry for each image of the image. And note that ADO_FIXED_LENTRY, ADO_NUMERIC_ENTRY, ADO_VARIABLE_ENTRY, and ADO_VARIABLE_LENTRY, and ADO_VARIABLE_LENTRY are selected depending on the case. 3. In your application, create an instance of the faction class. Get the IadorecordBinding interface from the RecordSet, then call the BindtoreCordSet method to bind all the fields of the Recordset to the corresponding C / C variables. See the sample program for more information. Interface Method Iadorecordbinding interface only three methods: bindtorecordset, addnew, and update. The unique parameter required for each method is an instance pointer for CadorecordBinding derived class. Therefore, the addNew and Update methods cannot use any parameters in the ADO method that are the same name. The syntax bindtorecordset method binds the field to the C / C variable. BindTorecordSet (CADORECORDBINDING * BINDING) AddNew method references its same name ADO function to add a new record line. AddNew (CADORECORDBINDING * BINDING) Update method also references its same name ADO function to update RecordSet. Update (CADORECORDBINDING * BINDING) Binding entry macro binding entry macro defines a reference relationship between a RECORDSET field and a variable. The binding macro of each entry consists of start macros and end macros and is paired. The macro of the fixed length data is suitable for addte, Adboolean et al, digital macro is suitable for ADTINYINT, AdINteger, and AddouBle, and the macro that makes the length of data is applied to Adchar, Advarchar, and Advarbinary. All digital types are also a fixed length data type except AdvarNumeric. There are different parameter groups between each macro, so you can exclude binding information that is not interested.

OLE DB Programmer's Reference See Appendix A: More information start data type binding entry BEGIN_ADO_BINDING (Class) fixed length data: ADO_FIXED_LENGTH_ENTRY (Ordinal, DataType, Buffer, Status, Modify) ADO_FIXED_LENGTH_ENTRY2 (Ordinal, DataType, Buffer, Modify) number data: ADO_NUMERIC_ENTRY (Ordinal, DataType, Buffer, Precision, Scale, Status, Modify) ADO_NUMERIC_ENTRY2 (Ordinal, DataType, Buffer, Precision, Scale, Modify) variable-length data: ADO_VARIABLE_LENGTH_ENTRY (Ordinal, DataType, Buffer, Size, Status, length , Modify) ADO_VARIABLE_LENGTH_ENTRY2 (Ordinal, DataType, Buffer, Size, Status, Modify) ADO_VARIABLE_LENGTH_ENTRY3 (Ordinal, DataType, Buffer, Size, Length, Modify) ADO_VARIABLE_LENGTH_ENTRY4 (Ordinal, DataType, Buffer, Size, Modify) end binding END_ADO_BINDING () parameters Describe the name of the Class derived class. Ordinal originates from 1, corresponding to the fields in the Recordset. DataType corresponds to the ADO data type corresponding to the C / C variable (see DataTyPeenum to get a list of valid data types). If necessary, the value of the field is converted to the value of this type. The name of the C / C variable corresponding to the buffer. Size The maximum number of bytes of the C / C variable. If it is a growing string, use 0 to represent it. STATUS indicates the name of the variable. This variable is used to indicate whether the buffer is valid, whether the data conversion is successful. The value Adfldok means the success of the conversion; AdfldNull means that the value of the field is empty. Other possible values ​​see the list of status values ​​later. Modify logic sign. TRUE means that ADO allows the value of the fields in the Recordset to be updated using variable values. Set this value to TRUE will allow updates, if you only want to check the value of the field instead, set it to false. The number of PRECISION digital variables. Scale digital variables of the number of decimal numbers. Length a 4-byte variable name. This variable will include the actual length of the data in the buffer. The value of the status value variable STATUS indicates whether the value of a field is successfully copied to the corresponding variable. When writing data, you can assign the Status to AdfldNull to indicate that the field will be set to NULL. A constant value describes Adfldok 0 A non-empty field value is returned. AdfldBadaccessor 1 is invalid. AdfldcantConvertValue 2 Values ​​cannot be properly converted due to symbol mismatch or excessive reason. When the AdfldNull 3 reads a field value, indicating an null value is returned. When writing field values, the field will be set to NULL when the field itself cannot encode null. Adfldtruncated 4 beats long data or numbers being truncated. The ADFLDSIGNMISMatch 5 value is a symbol number, and the data type is unsigned. AdfldDataOverflow 6 Data Value Beyond the boundaries. AdfldcantCreate 7 Unknown column types and fields have been opened. The Adfldunavailable 8 field value cannot be determined. For example, a new field that does not assign a default value. AdfldPermissionDenied 9 is not allowed to update data.

AdfldintegrityViological 10 Update field value violates the integrity requirements of the column. Adfldschemaviolation 11 Update field value violates the column specification requirements. When AdfldBadStatus 12 updates the field, the invalid status parameter is invalid. ADFLDEFAULT 13 When updating fields, use the default. Examples using VC to ADO Example In this example, the COM proprietary "Smart Pointer" function is also used, which automatically handles the QueryInterface and reference count of the IadoreCordBinding interface. If there is no smart pointer, you have to code this: Iadorecordbinding * picrs = null; ... testhr (PRS-> queryinterface (_UUIDOF (il), (lpvoid *) & picrs); ... if (picrs) Picrs-> Release _COM_SMARTPTR_TYPEDEF (IADORecordBinding, __uuidof (IADORecordBinding)); then such instances of pointers:: smart pointers, you can use this statement from IADORecordBinding interfaces derived IADORecordBindingPtr type; () IADORecordBindingPtr picRs (pRs); because VC extensions implemented by the Recordset object Therefore, the constructor of the smart pointer PICRS uses the _recordsetptr class pointer PRS. The constructor uses PRS to call QueryInterface to get an IadoreCordBinding interface. // The following is the example program #import "c: / program files / common files / system / ado / msado15.dll" / no_namespace rename ("eof", "endoffile" # include # include

_COM_SMARTPTR_TYPEDEF (IADORecordBinding, __uuidof (IADORecordBinding)); inline void TESTHR (HRESULT _hr) {if FAILED (_hr) _com_issue_error (_hr);} class CCustomRs: public CADORecordBinding {BEGIN_ADO_BINDING (CCustomRs) ADO_VARIABLE_LENGTH_ENTRY2 (2, adVarChar, m_ch_fname, sizeof (m_ch_fname ), m_ul_fnameStatus, false) ADO_VARIABLE_LENGTH_ENTRY2 (4, adVarChar, m_ch_lname, sizeof (m_ch_lname), m_ul_lnameStatus, false) END_ADO_BINDING () public: CHAR m_ch_fname [22]; CHAR m_ch_lname [32]; ULONG m_ul_fnameStatus; ULONG m_ul_lnameStatus;}; void main (void) {:: Coinitialize (NULL); try {_RecordSetPtr PRS ("AdoDb.Recordset"); CCUSTOMRS RS; IadorecordbindingPtr Picrs (PRS); PRS-> OPEN ("Select * from Employee Order By Lname", "DSN = PUBS; UID = SA; PWD =; ", AdopenStatic, AdlockOptimistic, AdcmdText); TESTHR (Picrs-> BindtorecordSet); While (! PRS-> endoffile) {// Processing data in CCUSTOMRS (" Name = % S% S / N ", (rs.m_ul_fnamestatus == adfldok? rs.m_ch_fname:" "), (rs.m_ul_lnamestatus == adfldok? rs.m_ch_lname:"

")); // Move to the next line, the value of the new row will be automatically filled in the corresponding CCUSTOMRS variables PRS-> MOVENEXT ();}} catch (_COM_ERROR & E) {Printf (" error: / n ") PRINTF ("CODE =% 08LX / N", E.Error ()); Printf ("Meaning =% S / N", E.ErrorMessage ()); Printf ("Source =% S / N", (LPCSTR E.Source ()); Printf ("Description =% S / N", (LPCSTR) E.DESCRIPTION ());} :: counitialize ();} Source: http://blog.9cbs.net/i_like_database /archive/2005/01/11/248985.aspx

转载请注明原文地址:https://www.9cbs.com/read-54859.html

New Post(0)