VC++通过ADO连接mysql中文显示问题

来源:互联网 发布:apache ab 和jmeter 编辑:程序博客网 时间:2024/06/13 23:28
VC++通过ADO连接mysql_ConnectionPtr pConn(__uuidof(Connection));
  _RecordsetPtr pRst(__uuidof(Recordset));
  CString strServer = "Localhost"; //本机服务器名称
  CString strDBFile = "xscj"; //数据库名
  CString strConn; //连接字符串
  strConn.Format(_T("Driver=MySQL ODBC 3.51 Driver;;charset=gbk;Server=%s;Database=%s;  
  UID=root;PWD=root"),strServer,strDBFile);  
  pConn->Open ((_bstr_t)strConn,"","",-1); 
  pRst=pConn->Execute("select * from xs",NULL,adCmdText);
  while(!pRst->rsEOF)
{
((CListBox*)GetDlgItem(IDC_LIST1))->AddString(
(_bstr_t)pRst->GetCollect("XM"));
pRst->MoveNext ();

}

 

首先要保证数据选用的编码格式为GBK(这是许多前辈们建议的,这个字符集支持的比较多),而且在MySql中还可以设置表的,字段的编码格式。

      其次,在ADO连接代码中做必要的设置,具体设置如下:

 

try  

{  

  //设置ADO使用的字符集   

 myConn->Execute("set character_set_connection=gbk",NULL,adCmdText);     

myConn->Execute("set character_set_results=gbk",NULL,adCmdText);     

 myConn->Execute("set character_set_client=gbk",NULL,adCmdText);    

 myConn->Execute(_bstr_t(sqlText),NULL,adCmdText);  

}  

catch (_com_error e)  

{  

 msg = e.ErrorMessage();  

}