VC操作Sqlserver

//在文件头上加入
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF") 
//连接SQLserver
void CTestSqlserverDlg::OnBnClickedBtnConn()
{
	
	/*
	其中://关闭数据库
void CTestSqlserverDlg::OnBnClickedBtnDbClose()
{
	m_pConnection->Close();
	m_pConnection.Release();
}
  ----- ADO连接SQL Server的数据库连接字符串模板 ---------- 身份验证模式为:"sql server和windows" Provider=SQLOLEDB.1;Persist Security Info=True;User ID=用户名;Password=密码;Initial Catalog=数据库名;Data Source=SQL服务器名 身份验证模式为:"仅windows" Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=数据库名;Data Source=SQL服务器名 */ CString strSQL; HRESULT hr; try { hr=m_pConnection.CreateInstance(__uuidof(Connection)); m_pConnection->CursorLocation=adUseClient; strSQL="Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Password=adminadmin;Initial Catalog=LocalDataAnalyticalSystem;Data Source=10.36.65.232"; if(SUCCEEDED(hr)) { hr=m_pConnection->Open(_bstr_t(strSQL),"","",-1); } } catch(_com_error e)///捕捉异常 { CString errormessage; errormessage.Format(_T("连接数据库失败!\r\n错误信息:%s"),e.ErrorMessage()); AfxMessageBox(errormessage);///显示错误信息 return; } /* HRESULT hr; try { hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象 if(SUCCEEDED(hr)) { hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb","","",adModeUnknown);///连接数据库 ///上面一句中连接字串中的Provider是针对ACCESS2000环境的,对于ACCESS97,需要改为:Provider=Microsoft.Jet.OLEDB.3.51; } } } catch(_com_error e)///捕捉异常 { CString errormessage; errormessage.Format(_T("连接数据库失败!\r\n错误信息:%s"),e.ErrorMessage()); AfxMessageBox(errormessage);///显示错误信息 } */ }
 简单查询 // 简单查询
void CTestSqlserverDlg::OnBnClickedBtnDb()
{
	//直接得到数据
	//CListCtrl* lstData=(CListCtrl*)this->GetDlgItem(IDC_LST_DATA);
	

	Command15Ptr pCommand;
	Recordset15Ptr pRs;
	pCommand.CreateInstance(__uuidof(Command));
	pCommand->ActiveConnection=(_ConnectionPtr)m_pConnection;
	pCommand->CommandText="select * from TBL_CFG_ROLES";
	pCommand->CommandType=adCmdText;
	pCommand->Parameters->Refresh();
	pRs=pCommand->Execute(NULL,NULL,adCmdUnknown);	

	/*
	long   nCount   =   pRs-> GetFields()-> GetCount(); 
	for (long i=0;i<nCount;i++)
	{
		_variant_t varValue = pRs->GetCollect("ROLE_NAME");
		//CString strValue=_bstr_t(varValue);
		//MessageBox(strValue);
		m_lstData.InsertItem(0,_bstr_t(varValue));		
	}
	*/

	m_lstData.InsertItem(0,_bstr_t(pRs->GetCollect(0L)));
	m_lstData.InsertItem(1,_bstr_t(pRs->GetCollect(1L)));
	m_lstData.InsertItem(2,_bstr_t(pRs->GetCollect(2L)));

	
	
	while(pRs->MoveNext())
	{
		m_lstData.InsertItem(0,_bstr_t(pRs->GetCollect(0L)));
		m_lstData.InsertItem(1,_bstr_t(pRs->GetCollect(1L)));
		m_lstData.InsertItem(2,_bstr_t(pRs->GetCollect(2L)));
	}
	
	
	pRs->Close();
	pRs.Release();
	pCommand.Release();	
}
 

你可能感兴趣的:(sql,SQL Server,Security,Microsoft,vc++)