以下代码部分为转载内容。在使用以下代码之前千万记得要先注册好自己连接的数据库,方法是进入“控制面板”,注册好OBDC数据源,具体方法网上查
http://news.ccidnet.com/art/32849/20100608/2081137_1.html
VS2008中首先新建个基于Dialog的MFC应用程序,然后经过wizard生成的stdafx.h文件的末尾添加上#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")
VS2008中首先新建个基于Dialog的MFC应用程序,然后经过wizard生成的stdafx.h文件的末尾添加上#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")
双击resouce view中dialog目录下的Dialog中的任意一个按钮
然后再Dlg.CPP按钮事件中添加如下代码
CoInitialize(NULL); //AfxOleInit(); _ConnectionPtr pConn(__uuidof(Connection)); _RecordsetPtr pRst(__uuidof(Recordset)); _CommandPtr pCmd(__uuidof(Command)); //实例化一个Command对象pCmd if (FAILED(pConn.CreateInstance("ADODB.Connection"))) { AfxMessageBox(L"Create Instance failed!"); return; } pConn->Open("Provider=SQLOLEDB.1; Integrated Security=SSPI; Initial Catalog=Component; Data Source=VISIONSKY \\sqlexpress;","","",adModeUnknown); AfxMessageBox(L"连接成功"); } catch(_com_error e) { AfxMessageBox(L"连接失败" +e.Description()); } |
这里使用的方法是windows验证,你也可以用混合验证
Provider=SQLOLEDB.1; Integrated Security=SSPI; Initial Catalog=Component; Data Source=VISIONSKY\\sqlexpress; 替换成 Provider=SQLOLEDB.1; Persist Security Info=False; User ID=sa;PWD=sa; Initial Catalog=Component; Data Source=VISIONSKY\\sqlexpress |
我的数据库用的是sql2005express,如果你用的是2005而不是express版本的,那么你需要将\\sqlexpress去掉即可