ADO ODBC操作MySQL 控制台小例

#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF") rename("BOF","adoBOF")
#include<iostream>
#include<string>
#include<objbase.h>

typedef std::string string;

int main(int argc, char** argv)
{
 ::CoInitialize(NULL);//初始化OLE/COM库环境
 try
 {
  //创建Connection对象 连接数据库
  _ConnectionPtr pConnection = NULL;
  pConnection.CreateInstance("ADODB.Connection");
  pConnection->Open("DSN=MSSTD; Server = localhost; Database=std", "root", "root", adModeUnknown);

  //创建记录集对象
  _RecordsetPtr pRecordset = NULL;
  pRecordset.CreateInstance(__uuidof(Recordset));
  //取得表中的记录
  _bstr_t bstrSQL = "select * from regist";
  pRecordset->Open(bstrSQL, pConnection.GetInterfacePtr(),adOpenDynamic, adLockOptimistic,adCmdText);
  if(!pRecordset->adoBOF)//The BOF property returns True (-1) if the current record position is before the first record in the Recordset, otherwise it returns False (0).
  {
   pRecordset->MoveFirst();
  }

  _variant_t RecordValue;

  while(!pRecordset->adoEOF)//The EOF property returns True (-1) if the current record position is after the last record in the Recordset, otherwise it returns False (0).
  {
   string str;
   RecordValue  = pRecordset->GetFields()->GetItem("username")->Value;
   _bstr_t tempbstr= static_cast<_bstr_t>(RecordValue);
   str = static_cast<std::string>(tempbstr);
   std::cout<<str<<"\t";

   RecordValue  = pRecordset->GetFields()->GetItem("password")->Value;
   tempbstr= static_cast<_bstr_t>(RecordValue);
   str = static_cast<std::string>(tempbstr);
   std::cout<<str<<"\t";
   std::cout<<std::endl;
   pRecordset->MoveNext();
  }
  //执行MySQL语句
  _bstr_t sql = "insert into regist(username, password) values('222','222')";
  pConnection->Execute(sql,NULL,adCmdText);

  pRecordset->Close();
  pConnection->Close();
  pRecordset = NULL;
  pConnection = NULL;
  //释放
  ::CoUninitialize();
 }
 catch(_com_error e)
 {
  std::cout<<e.Description()<<std::endl;
 }

 system("pause");
 return 0;
}

PS:

需要msado15.tlh 文件 放在 可执行程序同一目录下

另外使用前需要配置MySQL的ODBC驱动

你可能感兴趣的:(mysql,控制台,odbc,ADO)