HOWTO: Use ATL Consumer Classes to Connect to SQL Server (191746)



The information in this article applies to:

  • Microsoft OLE DB 2.0, when used with:
    • Microsoft Visual C++, 32-bit Enterprise Edition 6.0
    • Microsoft Visual C++, 32-bit Professional Edition 6.0
    • Microsoft Visual C++, 32-bit Learning Edition 6.0

This article was previously published under Q191746

SUMMARY

This article demonstrates how to use ATL Consumer Classes with the SQLOLEDB provider to connect to SQL Server 6.5, 7.0, and 2000.

MORE INFORMATION

The following sample code is an OLE DB Consumer Application that uses OLE DB Consumer Template classes. It demonstrates three ways to use the SQLOLEDB provider to connect to a SQL Server database.

Sample Code

Note You must change User ID <username> and Password <strong password> to the correct values before you run this code. Make sure that User ID has the appropriate permissions to perform this operation on the database.
   HRESULT hr ;

   //Initialize COM.
   hr = CoInitialize(NULL);

   CDataSource connection1 ;
   CDataSource connection2 ;
   CDataSource connection3 ;


   // ===================================================
   // Method #1: Setting OLE DB Initialization Properties
   // ===================================================
   CDBPropSet propset(DBPROPSET_DBINIT);
   propset.AddProperty(DBPROP_INIT_DATASOURCE, L"mySQLServer");
   propset.AddProperty(DBPROP_INIT_CATALOG, L"pubs");
   propset.AddProperty(DBPROP_AUTH_USERID, L"<username>");
   propset.AddProperty(DBPROP_AUTH_PASSWORD, L"<strong name>");
   hr = connection1.Open("SQLOLEDB", &propset);
   connection1.Close();

   // ===================================================
   // Method #2: Using MS Data Link dialog
   // ===================================================

   hr = connection2.Open(GetDesktopWindow());
   BSTR bstr;
   connection2.GetInitializationString(&bstr);
   // bstr contains the initialization string.
    connection2.Close();

   // ===================================================
   // Method #3: Supplying a provider string
   // ===================================================
   // This may take a relatively longer amount of time.

   hr = connection3.OpenFromInitializationString
        (L"Provider=SQLOLEDB;User ID=<username>;Password=<strong name>;Data Source=mySQLServer;
        Initial Catalog=pubs;");
   connection3.Close();
				

REFERENCES

MSDN Library Visual Studio 6.0.

The following article in the Microsoft Knowledge Base describes the requirements to add OLE DB template support to Visual C++ projects:

190959 PRB: OLE DB Consumer Template Wizard Requires ATL Project


Modification Type:MinorLast Reviewed:3/2/2005
Keywords:kbConsumer kbDatabase kbDTL kbhowto KB191746