Database Program Development Instance using ADO encapsulation [version 2] (on zz)

Source: Internet
Author: User
Tags mdb database
After posting the article "using ADO encapsulated database program development instances" in the VC knowledge base last time, I was very pleased with the response from many netizens. However, since I was not fully proficient in ADO, the class I wrote last time was not perfect and may even cause some friends a little trouble. Therefore, I always wanted to write it better.

Currently, this class function is well-developed. It basically encapsulates most of the methods of the ADO component and extends some common methods, such as writing files or images to the database, reads bitmap fields from the database, intelligently converts the values of fields, and so on.

Because it is really not enough time, I almost did not perform any effective tests on the command class, nor did I write relevant documents, and I am not very clear about the documents of the connection and recordset classes, maybe someone will say that I am irresponsible again. Haha!

In this test program, I tested most methods of the connection class and record set class, including accessing, adding, and deleting common data types, there are also variable reading for various data types, such as integer, double-precision, and character. The feature type has the best compatibility. Basically, a valid value can be returned for most data, followed by double-precision, and integer, they cannot read values of fields such as week type and date type. in addition, the attributes of these two images are tested. Of course, many attributes cannot be fully tested.

I have learned several useful methods in developing ado-related programs, such as setfilter, setsort, find, and bookmarks. They allow you to effectively manipulate records, instead of thinking about how to build SQL statements to implement this function.

There is also a method for importing and exporting XML files. I don't know if this method is very useful, because it does not support Chinese well, and the exported XML file cannot display Chinese normally.
The last one is to bind the DataGrid Control to the record set. I think this should be a useful technique. I have never thought of it before. In VC, I can also learn to bind a database like VB, in this way, you can easily modify data without writing any code.

The code is compiled in (vc6 + SP5)/vc7 + Windows XP English Professional Edition/Windows 2000 Chinese Professional Edition/Windows 2003 English test edition/Windows 2003 Chinese Enterprise Edition, and in access, sqlserver, mySQL is tested. Except MySQL does not support transactions and other methods, most methods can pass the test.
In principle, I acquiesce in your freedom to use, modify, or spread this Code. However, if you use this code in a certain project or for commercial purposes, please note that, I will not be liable for any losses caused to you due to code bugs or copyright issues.
Since we have encapsulated so many things for the first time that we are not very familiar with, please give us more advice on any improper things.

Run the following code:
Http://www.vckbase.com/document/journal/vckbase21/images/MyAdo21.gif

The following describes the encapsulation classes in detail:

Cadoconnection class

Class member:

Constructor: cadoconnection ()
Create a connection object.

Open method:

Bool cadoconnection: open (lpctstr lpszconnect, long loptions)
Connect to the data source.

Params:
[Lpszconnect]: connection string, including connection information.
[Loptions]: (optional) determines whether to connect to the data source in synchronous or asynchronous mode. It can be a constant as follows:

[Constant] [Description]
Adconnectunspecified (Default) Enable the connection in synchronous mode.
Adasyncconnect Asynchronously open the connection.
Ado uses the connectcomplete event to notify that the connection has been completed.

Bool cadoconnection: connectsqlserver (cstring dbsrc, cstring dbname, cstring user, cstring pass, long loptions)
Connect to the SQL Server database.

Bool cadoconnection: connectaccess (cstring dbpath, cstring pass, long loptions)
Connect to the access database.

Params:
[Dbpath]: Path Name of the access mdb database file.
[Pass]: access password.
[Dbsrc]: SQL Server server name.
[Dbname]: default database name.
[User]: user name.

Openudlfile method:

Bool cadoconnection: openudlfile (lpctstr strfilename, long loptions)
Open the udl file to connect to the database.

Params:
[Strfilename]: Path Name of the udl database connection file.

// SQL server access example:

CAdoConnection pAdoConnection;CString strConnection = _T("Provider=SQLOLEDB.1;Persist Security Info=False;""Integrated Security=SSPI;""Data Source=cz\\xyy;Initial Catalog=NoteBook;");if (pAdoConnection.Open(LPCTSTR(strConnection))){DoSomething();}...

Or:

if (pAdoConnection.ConnectSQLServer("cz\\xyy", "NoteBook", "sa", "007")){DoSomething();}

// Access example:

CAdoConnection pAdoConnection;CString strConnection = _T("Provider=Microsoft.Jet.OLEDB.4.0;"   "Data Source=C:\\dbTest.mdb");pAdoDb.SetConnectionString(strConnection);if (pAdoConnection.Open(LPCTSTR(strConnection))){DoSomething();}...

Or:

if (pAdoConnection.ConnectAccess("C:\\dbTest.mdb", "007")){DoSomething();}...

Close method:
Void cadoconnection: Close ()
Close the connection to the data source.
Remarks: Close the connection object to release all associated system resources. closing an object does not delete it from memory. You can change its attribute settings and enable it again later. this method is automatically called when the connection object scope is exceeded or the new database is reconnected.

Execute method:
_ Recordsetptr cadoconnection: Execute (lpctstr lpszsql, long loptions)
Execute the specified query, SQL statement, and stored procedure.
Remarks: see the open method of the cadorecordset class. the returned recordset object is always a read-only, forward-only cursor. this method is generally used to execute SQL statements that do not return record sets. it is more flexible to use the recordset object to execute a small statement.

For example:

if (pAdoConnection.IsOpen()){pAdoConnection.Execute("Delete From student Where number = 3");}

Cancel Method:
Bool cadoconnection: Cancel ()
Remarks: see cadorecordset cancel method.

Getlasterrortext method:
Cstring cadoconnection: getlasterrortext ()
Obtain the last error message.
Remarks: any operation involving an ADO object can generate one or more provider errors. when an error occurs, you can place one or more error objects in the errors collection of the connection object. when errors are generated by other ADO operations, the errors set is cleared and the new error object is placed in the errors set. each error object represents a specific provider error, not an ADO error. ado errors are recorded in the exception handling mechanism at runtime. no wrong ADO operation has no effect on the errors set. you can use the clear method to manually clear the errors set.

Errorsptr cadoconnection: geterrors ()
Obtains the object pointer of the error set.

Errorptr cadoconnection: geterror (long index)
Get error object pointer.

Isopen attributes:
Bool cadoconnection: isopen ()
Checks whether the connection object is open.

Connecttimeout attributes:
Bool cadoconnection: setconnecttimeout (long ltime)
Long cadoconnection: getconnecttimeout ()
Set or obtain the connection timeout.

Providername attributes:
Cstring cadoconnection: getprovidername ()
Obtain the name of the connection object provider.

Version attribute:
Cstring cadoconnection: getversion ()
Obtain the version number of the currently used ADO

State attribute:
Long cadoconnection: getstate ()
Get the object state (same as the getstate method of the recordset object ).
Returns: return the long integer value of one of the following constants (the connection object is generally one of the following two States ).

[Constant] [Description]
Adstateclosed Indicates that the object is closed.
Adstateopen Indicates that the object is open.

Remarks: You can use the state attribute to obtain the current state of a specified object at any time.

Mode attribute:
Connectmodeenum cadoconnection: getmode ()
Bool cadoconnection: setmode (connectmodeenum Mode)
Set or obtain the available permissions to modify data in the connection object.
Returns: returns the value of connectmodeenum.

[Constant] [Description]
Admodeunknown The default value indicates that the permission has not been set or cannot be determined.
Admoderead Indicates that the permission is read-only.
Admodewrite Indicates that the permission is write-only.
Admodereadwrite Indicates that the permission is read/write.
Admodesharedenyread Prevent other users from using the read permission to open the connection.
Admodesharedenywrite Prevent other users from using the write permission to open the connection.
Admodemo-exclusive Prevent other users from opening the connection.
Admodesharedenynone Prevent other users from using any permissions to open the connection.

Remarks: You can use the mode attribute to set or return the access permission that is being used by the provider on the current connection. You can only set the mode attribute when closing the connection object.

Openschema method:

_ Recordsetptr cadoconnection: openschema (schemaenum querytype)
Obtain database information from the data source.

Params: [querytype]: Query type of the mode to be run. The following lists some common types and the main field names in multiple fields in the returned table.

Adschemaasserts Constraint_name
Adschemacatalogs Catalog_name
Adschemacharactersets Character_set_name
Adschemacheckconstraints Constraint_name
Adschemacollations Collation_name
Adschemacolumndomainusage Domain_name
  Column_name
Adschemacolumnprivileges Table_name
  Column_name
  Grantor
  Grantee
Adschemacolumns Table_name
  Column_name
Adschemaconstraintcolumnusage Table_name
  Column_name
Adschemaconstrainttableusage Table_name
Adschemaforeignkeys Pk_table_name
  Fk_table_catalog
  Fk_table_schema
  Fk_table_name
Adschemaindexes Index_name
  Type
  Table_name
Adschemakeycolumnusage Constraint_name
  Table_catalog
  Table_schema
  Table_name
  Column_name
Adschem1_marykeys Pk_table_name
Adschemaprocedurecolumns Procedure_name
  Column_name
Adschemaprocedureparameters Procedure_name
  Paramter_name
Adschemaprocedures Procedure_name
  Procedure_type
Adschemaproviderspecific See description
Adschemaprovidertypes Data_type
  Best_match
Adschemareferentialconstraints Constraint_name
Adschemaschemata Schema_owner
Adschemasqllanguages <None>
Adschemastatistics Table_name
Adschematableconstraints Constraint_name
  Table_catalog
  Table_schema
  Table_name
  Constraint_type
Adschematableprivileges Table_name
  Grantor
  Grantee
Adschematables Table_name
  Table_type
Adschematranslations Translation_name
Adschemausageprivileges Object_name
  Object_type
  Grantor
  Grantee
Adschemaviewcolumnusage View_name
Adschemaviewtableusage View_name
Adschemaviews View_name

Returns: returns the recordset object containing database information. recordset will be opened with a read-only and static cursor.
Remarks: The openschema method returns information related to the data source, such as the table on the server and the column in the table. The above data is for reference only, depending on the specific data source.

Trans related methods:
Long cadoconnection: begintrans ()
Bool cadoconnection: committrans ()
Bool cadoconnection: rollbacktrans ()
Begintrans-start a new transaction.
Committrans-save any changes and end the current transaction. It may also start a new transaction.
Rollbacktrans-cancels any changes made in the current transaction and ends the transaction. It may also start a new transaction.

Once the begintrans method is called, the database will no longer commit any changes made immediately before calling committrans or rollbacktrans to end the transaction.
For databases that support nested transactions, calling the begintrans method in opened transactions starts new nested transactions. the returned value indicates a nested level. If the returned value is 1, the top-level transaction has been opened (that is, the transaction is not nested by another transaction ), 2 indicates that the second-level transaction has been opened (the transaction nested in the top-level transaction), and so on. calling committrans or rollbacktrans only affects the latest opened transactions. You must close or roll back the current transaction before processing any higher-level transactions.
Calling the committrans method will save the changes made in the transaction opened on the connection and end the transaction. call the rollbacktrans method to restore the changes made in the transaction and end the transaction. an error occurs when any method is called before a transaction is opened.

// Numeric type conversion ----------------------------------- coledatetime vartodate (const _ variant_t & var); colecurrency vartocy (const _ variant_t & var); bool vartobool (const _ variant_t & var ); byte vartoby (const _ variant_t & var); short vartoi (const _ variant_t & var); long vartol (const _ variant_t & var); double vartof (const _ variant_t & var ); cstring vartostr (const _ variant_t & var );

Converts a type variable to another type variable.

Database Program Development Instance using ADO encapsulation class[Version 2] (lower)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.