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中的任意一个按钮
然后再<ProjectName>Dlg.CPP按钮事件中添加如下代码
复制代码
这里使用的方法是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去掉即可
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rsEOF")
双击resouce view中dialog目录下的Dialog中的任意一个按钮
然后再<ProjectName>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());
-
- }
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去掉即可