How should VC ++ programmers read ADO documents

xiaoxiao2021-03-06  39

How should VC programmers read ADO documents

The "ADO API Reference" describes the contents of the ADO API with the VB's grammar. 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).

Compile the indicator using #import

#import Compilation Indicator makes the method using ADO and the properties simplified. 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 properties:

Variable = Objectptr-> getProperty (); // read the value of the attribute

ObjectPtr-> PutProperty (value); // Set the value of the property

ObjectPtr-> PutRefProperty (& value); // Set the value of a pointer type attribute

Direct use properties

__declspec (property ...) Compilation indicator is a Microsoft definition of an extension for the C language, making a function as used as an attribute. This way you can use the following grammatical form to read and write a value of an attribute like using VB: ObjectPtr-> Property = value; // Set the value of the property

Variable = ObjectPtr-> Property; // Read the value of the attribute

__Declspec (Property ...) Compile indicator can only be used for read and write functions of the attribute, and whether 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 defines 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 elements:

CollectionPtr-> GetItem (Index);

Collectionptr-> item [index];

For example, you want to assign a value in a RecordSet object RS, and this Recordset object is derived from 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

In general, the data type of VB you see in "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, the data type, which is being used is: 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

Usually when a _variant_t or _bstr_t parameter is transmitted to an operation, there is no need to explicit type conversion code. 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 of the RECORDSET :: Open method is declared as follows:

HRESULT OPEN

Const _variant_t & source,

Const _variant_t & ActiveConnection,

ENUM CURSORTYPEENUM CURSORTYPE,

ENUM LOCKTYPEENUM LOCKTYPE,

Long Options;

The parameter ActiveConnection is a reference for a variant_t type variable, which 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 whether the constructor of the variant calls the embedded addRef () method, and is automatically called after completing the ADO method or attribute call _variant_t :: release () method

SafeArray

SafeArray is also a structured data type that includes an array composed of data elements 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.

Default parameters

VB allows certain parameters of the method of 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

Parameters Recordsaffected and Parameters are pointers to 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 the parameters are not available, you need to set parameters to & VTMissing (recommended) or an empty pointer. 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);

Incorrect processing

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.

At the time of encoding in VC and VB

Below is an overview of how to write code using VB and VC in the ADO documentation.

Declare an ADO object

In VB, an ADO object variable (here, the RECORDSET object is an example) declaration:

DIM RST As Adodb.Recordset

The clause "AdoDb.Recordset" is the ProgID of the Recordset object registered in the registry. And an example of a Record object, as follows: 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, the data type of the pointer variable pointing to the _Recordset object is _RecordSetPtr, and the following statement:

_RecordSetPtr RS;

And an example 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: 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.

Write the code of the String parameter

When you need to use the VB to write code to omit the String parameter, just simply slightly remove the operand. But in VC , you must specify that the operand is a _BSTR_T variable containing an empty string: _BSTR_T STRMISSING (L ");

Write the code to omit the Variant parameter

When you need to use VB to write code to omit the Variant parameter, you only need to simply ignore the 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 ...

Declare 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 arrays

In VB, the Variant array can be programmed by using the DIM statement and can be used using the 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", ""

RS = cn.openschema (Adschemacolumns, _

Array (EMPTY, EMPTY, "Authors", EMPTY)

For Each Fld in rs.fields

Debug.print "name ="; fld.name

Next FLD

Rs.close

Cn.close

End Sub

The following code demonstrates how to use a SafeArray array through a _variant_t. 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 SafeArrayCreate:

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;

It is actually more like letting _variant_t management SafeArray.

The complete code is as follows:

#import "c: / program files / compon 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"),

VtRiteria;

Long ix [1];

SafeArray * psa = null;

PCN-> Open ("DSN = PUBS; user ID = sa; pwd =; provider = msdasql;" "", ",

AdconnectunSpecified;

// Note 2, Note 3

PSA = SafeArrayCreateVector (VT_VARIANT, 1, 4);

IF (! PSA) _COM_ISSUE_ERROR (E_OUTOFMEMORY);

/ / Assign a value to the third element Table_name (index value 2).

IX [0] = 2;

TESTHR (SafearrayPuteElement (PSA, IX, & VTTABLENAME);

// Due to Variant does not have a SafeArray constructor, the data type and value of Variant is handled manually.

VtRiteria.vt = vt_Array | vt_variant;

VtRiteria.Parray = PSA;

PRS = PCN-> OpenSchema (Adschemacolumns, vtriteria, vtmissing);

Long limit = prs-> getfields () -> count;

For (long x = 0; 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 ();

}

Get / Put / Putref using properties

In VB, the name of the attribute is not verified, no matter whether it is read, assigned, or gives a 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 a demo of VC about GET / PUT / PUTREFPROPERTY

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 / compon 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 STRMISSING (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-> pactionsize;

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 ();

}

Use GetItem (X) and Item [x]

Below is a demonstration of standard and interactive syntax for Item () in VB.

Public SUB GetItemItem

DIM RS As New Adodb.Recordset

DIM Name as String

RS = rs.open "Authors", "DSN = Pubs;", AdoPENDYNAMIC, _

Adlockbatchoptimistic, ADTABLE

Name = rs (0)

'-or-

Name = rs.fields.Item (0)

RS (0) = "test"

Rs.Updatebatch

'Restore Name

RS (0) = Name

Rs.Updatebatch

Rs.close

End Sub

The following is VC about Item.

When accessing 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 / compon 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",

"Provider = SQLOLEDB; DATA SOURCE = a-TIMA10;"

"Initial Catalog = PUBS; User ID = SA; Password =;",

AdoPenStatic, AdlockOptimistic, Adcmdtable;

RS-> MoveFirst ();

// Note 1. Name of a field

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) 2) -> 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 ();

}

Transfer the pointer type for converting ADO objects using (iDispatch *)

1. 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 / compon 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;"

"Initial Catalog = 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 ();

}

Catch (_COM_ERROR & E) {

Printf ("Description = '% s' / n", (char *) E.DESCRIPTION ());

}

:: Couninitialize ();

}

///

VC extension to ADO

///

For VC programmers, each time you have to convert the data returned to a general C data type each time, then store 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 ADO expansion

Iadorecordbinding interface

VC Connects to ADO or bounds all fields to C / C variables for a 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

The extension of VC for ADO is image (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 of reading and writing data)

Top file required

In order to use VC to the ADO extension, you have to include this header file in your application: #include

Bind the field of Recordset

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

There is only three ways of Iadorecordbinding interface: 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.

grammar

The BindtorecordSet method is bound to the C / C variable.

BindtorecordSet (Cadorecordbinding * Binding)

The AddNew method references its same name ADO function to add a new record line.

AddNew (Cadorecordbinding * Binding)

The UPDATE method also references its co-name ADO function to update the Recordset.

Update (cadorecordbinding * binding)

Binding entry Hong

The binding entry macro defines a correspondence 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.

See OLE DB Programmer Reference Appendix A: More Information for Data Types

Start binding entry

Begin_ado_binding (class)

Delivery data:

ADO_FIXED_LENGTH_ENTRY (Ordinal, Datatype, Buffer, Status, Modify)

ADO_FIXED_LENGTH_ENTRY2 (Ordinal, DataType, Buffer, Modify)

Digital data:

ADO_NUMERIC_ENTRY (Ordinal, Datatype, Buffer, Precision, Scale, Status, Modify)

ADO_NUMERIC_ENTRY2 (Ordinal, Datatype, Buffer, Precision, Scale, Modify)

Growth 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 ()

parameter

description

Class

Delicious name.

ORDINAL

The serial number starting from 1 corresponds to the fields in the Recordset.

DataType

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.

Buffer

The name of the corresponding C / C variable.

Size

The maximum number of bytes of this 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

Logical logo. 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.

Precision

Digital variables of digital variables.

Scale

Digital variables of digital variables.

Length

A 4-byte variable name. This variable will include the actual length of the data in the buffer.

Status value

The value of the 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.

constant

value

description

ADFLDOK

0

A non-empty field value is returned.

AdfldBadaccessor

1

Binding is invalid.

AdfldcantConvertValue

2

The value is not possible to correctly convert because the value of the symbol mismatch or the reason is exceeded.

Adfldnull

3

When the field value is read, an null value is indicated returned. When writing field values, the field will be set to NULL when the field itself cannot encode null.

Adfldtruncated

4

Growth data or digital is truncated.

AdfldsignMismatch

5

The value is the number of symbols, and the data type is unsigned.

AdfldDataOverflow

6

The data value exceeds the boundary.

Adfldcantcreate

Seduce

Unknown column types and fields have been opened.

Adfldunavailable

8

The field value cannot be determined. For example, a new field that does not assign a default value.

AdfldPermissionDenied

9

Updated data is not allowed.

AdfldintegrityViology

10

The value of the update field violates the integrity requirements of the column.

Adfldschemaviology

11

The value of the update field violates the column specification requirements.

Adfldbadstatus

12

When updating the field, the invalid status parameter is updated.

Adflddefault

13

Use the default value when the field is updated.

Example of expanding ADO using VC

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 (Iadorecordbinding), (LPVOID *) & PICRS)))));

...

IF (Picrs) Picrs-> Release (); use smart pointers, you can use this statement from the Iadorecordbinding interface to the IadorecordbindingPtr type:

_COM_SMARTPTR_TYPEDEF (Iadorecordbinding, __UUIDOF (Iadorecordbinding);

Then this instantiate the pointer:

IadorecordbindingPtr Picrs (PRS);

Because the extension of VC is implemented by the Recordset object, 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 an example program

#import "c: / program files / compon 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)

{

/ / Handling data in CCUSTOMRS

Printf ("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 row, the value of the new row will be automatically filled into 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 ());

}

:: Couninitialize ();

}

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

New Post(0)