VC++中使用ADO访问SQL Server 2000简介

1.导入相关库文件(一般在StdAfx.h中导入)        
#import "c:\program files\common files\system\ado\msado15.dll"

no_namespace rename("EOF","adoEOF")

2.初始化COM库(一般在InitInstance()中初始化)
BOOL CXXXXAPP::InitInstance()

{

       AfxOleInit()

       ...........

       return FALSE;

}

 

3.实例化连接对象

(1)定义一个成员变量

_ConnectionPtr m_pConnect;

(2)实例化m_pConnect

BOOL CXXXDLG::OnInitDialog()

{

       m_pConnect.CreateInstance(__uuidof(Connection));

      ......

       return TRUE;

}

 

4.连接数据库
try

{

       m_pConnect->Open("Provider=SQLOLEDB;Data Source=服务器;Initial Catalog=数据库;","sa","123456",-1);

       MessageBox("连接数据库成功");

}
catch(_com_error e)
{

       AfxMessageBox(e.ErrorMessage());

       return;

}

5.数据库操作
m_pConnect->Execute("delete from TBL_CONNECTLOGS",NULL,adCmdText);

 

6.关闭连接
void XXXX::OnDestroy()

{

       if(m_pConnect->State)

       {

              m_pConnect->Close();

       }

       m_pConnect=NULL;

}

 

补充:连接字符串的模式
一般模式(SQL SERVER 身份验证)
"Provider=SQLOLEDB;Data Source=服务器;Initial Catalog=数据库;uid=SQL用户名;pwd=SQL密码;"

m_pConnect->Open("Provider = SQLOLEDB;Data Source=MICROSOF-32ADC5;Initial Catalog = Employee;","huxiaoke","123456",-1);

 信任模式(Windows 身份验证)
"Provider=SQLOLEDB;Data Source=服务器;Initial Catalog=数据库;Integrated Security=SSPI;" 

m_pConnect->Open("Provider = SQLOLEDB;Data Source=MICROSOF-32ADC5;Initial Catalog = Employee;Integrated Security=SSPI;","","",-1);

网络模式
"Provider=SQLOLEDB;Data Source=IP地址,端口;Network Library=DBMSSOCN;Initial Catalog=数据库;UserID=用户名;Password=密码;" 

注意看下面这两种写法,其实是一个意思:
m_pConnect->Open("Provider=SQLOLEDB;Data Source=服务器;Initial Catalog=数据库;","sa","123456",-1);

m_pConnect->Open("Provider=SQLOLEDB;Data Source=服务器;Initial Catalog=数据库;uid=sa;pwd=123456;","","",-1); 


Open函数的原型:

inline HRESULT Connection15::Open ( _bstr_t ConnectionString, _bstr_t UserID, _bstr_t Password, long Options );

本文地址:http://zhidao.baidu.com/question/273093565.html?pt=dwso...

 

你可能感兴趣的:(sql,数据库,server,Security,服务器,vc++,library)