近日学习VC 连接 SQL Server 数据库,遇到了问题.已经成功用OBDC_LESS 方法和OLEDB方法连接上数据库,现在用System DSN Connection 方法连接却遇到了麻烦,总是提示[Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序
下面是部分代码,请问该如何该连接字符串.(只要带DSN的连接字符串,别改成OLEDB的了,那个我已经会了。)PS:lj是我建立的数据源名称。
        
        CoInitialize(NULL);
_ConnectionPtr m_pLiuConnection;
HRESULT hr = m_pLiuConnection.CreateInstance(__uuidof(Connection));
if (!SUCCEEDED(hr))
{
return;
}
m_pLiuConnection->PutProvider("SQLOLEDB");
CString strConnection = "DSN =lj;UID = sa; PWD = sa";
m_pLiuConnection->ConnectionTimeout = 120;
try
{
m_pLiuConnection->Open((_bstr_t)strConnection,"","",NULL);
}
catch (_com_error &e)
{
MessageBox(e.Description(),"警告",MB_OK | MB_ICONWARNING);
}
该如何改,请大家指教,不甚感谢!我新手,分不多,以后多了再奉送!

解决方案 »

  1.   

    try
    {
    // 创建Connection对象
    m_pConnection.CreateInstance("ADODB.Connection");
    // 设置连接字符串,必须是BSTR型或者_bstr_t类型
    _bstr_t strConnect = "Provider=MSDASQL.1;Persist Security Info=False;User ID=;Data Source=;"; m_pConnection->Open(strConnect,"","",adModeUnknown);
    }
    // 捕捉异常
    catch(_com_error e)
    {
    // 显示错误信息
    AfxMessageBox(e.Description());
    }
      

  2.   


    mssql :
    ::CoInitialize(NULL);
      
    try
    {
    // 创建Connection对象
    m_pConnection.CreateInstance("ADODB.Connection");
    // 设置连接字符串,必须是BSTR型或者_bstr_t类型
    CString strSRC;
    strSRC="Driver=SQL Server;Server=";
    strSRC+="servername";
    strSRC+=";Database=";
    strSRC+="dbname";
    strSRC+=";UID=SA;PWD=";
    _bstr_t strConnect(strSRC);
    m_pConnection->Open(strConnect,"","",adModeUnknown);
    // AfxMessageBox("hi ,database !!");
    }
    // 捕捉异常
    catch(_com_error e)
    {
    // 显示错误信息
    AfxMessageBox(e.Description());
    }
      

  3.   

    上面这位大侠说的方法是对的,担不是我想要的,我现在需要的是DSN连接方法,就是连接字符串一定要有DSN=...的,还有一问,m_pLiuConnection.CreateInstance(__uuidof(Connection))和 m_pConnection.CreateInstance("ADODB.Connection");有什么区别啊?      CoInitialize(NULL); 
    _ConnectionPtr m_pLiuConnection; 
    HRESULT hr = m_pLiuConnection.CreateInstance(__uuidof(Connection)); 
    if (!SUCCEEDED(hr)) 

    return; 

    CString strConnection = "DSN =lj;UID = sa; PWD = sa"; 
    m_pLiuConnection->ConnectionTimeout = 120; 
    try 

    m_pLiuConnection->Open((_bstr_t)strConnection,"","",NULL); 

    catch (_com_error &e) 

    MessageBox(e.Description(),"警告",MB_OK | MB_ICONWARNING);