vs2005 sqlserver2005 連接、查詢

// char_.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"

#include <afx.h>
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define WIN32_LEAN_AND_MEAN  // Exclude rarely-used stuff from Windows headers
#include <tchar.h>

 

//使用# import把動態連接庫msado15.dll導入Visual C++應用程序,並生成定義ADO庫的兩個C++頭文件:msado15.tlh和ado15.tli。即:

#import "c:\Program Files\Common Files\System\ADO\msado15.dll"     no_namespace rename("EOF", "adoEOF")

void main()
{
 char * sqlCommand = "select * from dbo.db_test";
                                                                                                  
 _bstr_t strConnect="driver={SQL Server};Server=127.0.0.1;Database=view;uid=sa;pwd=Rootroot1;";
 ::CoInitialize(NULL);//初始化COM庫
 //添加一個指向Connection對象的指針m_pConnection
  _ConnectionPtr m_pConnection(__uuidof(Connection));

 if( FAILED( m_pConnection.CreateInstance(__uuidof(Connection)) ) ) //創鍵Connection對象
 {
  printf("創鍵Connection對象時出錯\n");
 }
 try
 {
  m_pConnection->Open (strConnect,"","", adModeUnknown); //連接數據庫
 }
 catch(_com_error e) 
 {
  MessageBox(NULL,e.Description(),L"test",1);
  //printf("連接數據庫時出錯\n");
 }

 m_pConnection->Execute(sqlCommand, NULL, 1);//執行SQL語句
 _RecordsetPtr m_pRecordset(__uuidof(Recordset));
 m_pRecordset.CreateInstance(__uuidof(Recordset));
 m_pRecordset->Open(sqlCommand, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);

 while(m_pRecordset->adoEOF==0)
 {
  printf("%s\n", (char*)(_bstr_t)m_pRecordset->GetCollect("id"));
  printf("%s\n", (char*)(_bstr_t)m_pRecordset->GetCollect("name"));
  printf("%s\n", (char*)(_bstr_t)m_pRecordset->GetCollect("salary"));
  m_pRecordset->MoveNext();
  
 }

 m_pRecordset->Close();
 m_pConnection->Close(); 
 ::CoUninitialize(); //釋放程序佔用的COM 資源 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章