Microsoft KB Archive/191746

= HOWTO: Use ATL Consumer Classes to Connect to SQL Server =

Article ID: 191746

Article Last Modified on 3/2/2005

-

APPLIES TO

 Microsoft OLE DB 2.0, when used with:  Microsoft Visual C++ 6.0 Enterprise Edition

 Microsoft Visual C++ 6.0 Professional Edition

 Microsoft Visual C++ 6.0 Standard Edition 

-

<div class="notice_section">

This article was previously published under Q191746

<div class="summary_section">

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.

<div class="moreinformation_section">

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 and 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" "); 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= ;Password= ;Data Source=mySQLServer;       Initial Catalog=pubs;"); connection3.Close;

<div class="references_section">