HOWTO: Use ATL Consumer Classes to Connect to SQL Server

ID: Q191746


The information in this article applies to:


SUMMARY

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


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


   HRESULT hr ;

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

   CDataSource connection1 ;
   CDataSource connection2 ;
   CDataSource connection3 ;

   // The examples assume that the SQL Server 'mySQLServer'
   // has an 'sa' account with no password.
   // ===================================================
   // 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"sa");
   propset.AddProperty(DBPROP_AUTH_PASSWORD, L"");
   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=sa;Password=;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:

Q190959 PRB: OLE DB Consumer Template Wizard Requires ATL Project


Keywords          : kbATL kbDatabase kbOLEDB kbVC600 kbConsumer 
Version           : WINNT:6.0
Platform          : winnt 
Issue type        : kbhowto 

Last Reviewed: July 21, 1999