MFC连接SQLServer2005数据库

时间:2023-01-26 04:35:10

MFC连接SQLServer2005数据库MFC连接SQLServer2005数据库其步骤一般分为:

(1)     引入ADO动态库文件

(2)     初始化COM环境

(3)     连接数据库操作数据表

说明:本数据库使用SQLServer2005制作,名字为“student”。内含一个表,命名为“stud”。

建表语句

create table stud
(
num varchar(7),
name nvarchar(20) not null,
gender nchar(2) default '男' check(gender in('男','女')),
dept nvarchar(20) not null
)

插入一些数据

insert into stud values('0147256','test','男','计算机系');

进行疯狂复制,多添加一些数据

insert into stud select * from stud;

本例中创建的数据源名字为'test'

需要添加数据源


stdafx.h添加以下代码引入ADO动态库文件

 

#import "C:\Program Files\CommonFiles\System\ado\msado15.dll" no_namespace\rename("EOF","adoEOF")rename("BOF","adoBOF")

 

初始化COM环境

 

::CoInitialize(NULL);   //在app类中的InitInstance函数中添加

::CoUninitialize();       //在app类中的InitInstance函数的最后(return之前)添加,释放COM环境

 

 

首先先在dlg头文件中先声明这两个智能指针,通过这些指针可以很容易的创建和删除ADO对象。

       _ConnectionPtrm_pConnection;

       _RecordsetPtrm_pRecordset;

 

接下来在dlg类中添加函数void OnInitADOConn()

void CMy1Dlg::OnInitADOConn()

{

      

::CoInitialize(NULL);          //初始化COM环境
try
{
//创建连接对象实例
m_pConnection.CreateInstance("ADODB.Connection");

CString strConnect;

//注意,我这里写的连接字符串是通过以下步骤的得到的:

//1、新建一个文件,名字任意取,后缀名必须为udl(如何hello.udl)

//2、双击hello.udl文件,进入数据连接属性面板,填写好数据源(选择自己创建的数据源名字的)

//3、再以记事本方式打开,第三行的数据就是连接字符

strConnect="Provider=MSDASQL.1;Persist Security Info=False;User ID=sa;Data Source=test;Password=*******";
//使用Open方法连接数据库
m_pConnection->Open((_bstr_t)strConnect,"","",adModeUnknown);  
}
catch(_com_error e)
{
AfxMessageBox(e.Description());
}

}

dlg类中在添加void ExitConnect()函数

void CMy1Dlg::ExitConnect()

{

       //关闭记录集和连接

       if(m_pRecordset!=NULL)

              m_pRecordset->Close();

       m_pConnection->Close();

}

dlg类的OnInitDialog函数中添加如下代码,设置列表视图的风格和标题(写在最后)

 

       m_Grid.SetExtendedStyle(LVS_EX_FLATSB

              |LVS_EX_FULLROWSELECT

              |LVS_EX_HEADERDRAGDROP

              |LVS_EX_ONECLICKACTIVATE

              |LVS_EX_GRIDLINES);

       m_Grid.InsertColumn(0,"编号",LVCFMT_LEFT,110,0);

       m_Grid.InsertColumn(1,"姓名",LVCFMT_LEFT,110,1);

       m_Grid.InsertColumn(2,"性别",LVCFMT_LEFT,110,2);

       m_Grid.InsertColumn(3,"学历",LVCFMT_LEFT,110,3);

       AddToGrid();

 

dlg类中添加void AddToGrid()函数

 

void CMy1Dlg::AddToGrid()

{

       //连接数据库

       OnInitADOConn();

       //设置查询字符串

       _bstr_tbstrSQL = "select * from stud";

       //创建记录集指针对象实例

       m_pRecordset.CreateInstance(__uuidof(Recordset));

       //打开记录集

       m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,

              adLockOptimistic,adCmdText);

int i=0;

       while(!m_pRecordset->adoEOF)

       {

              m_Grid.InsertItem(i,"");

              m_Grid.SetItemText(i,0,(char*)(_bstr_t)m_pRecordset->GetCollect("num"));

              m_Grid.SetItemText(i,1,(char*)(_bstr_t)m_pRecordset->GetCollect("sex"));

              m_Grid.SetItemText(i,2,(char*)(_bstr_t)m_pRecordset->GetCollect("gender"));

              m_Grid.SetItemText(i,3,(char*)(_bstr_t)m_pRecordset->GetCollect("dept"));

//两种方式均可

/*

m_Grid.SetItemText(i,0,(_bstr_t)m_pRecordset->GetCollect(_variant_t((long)0)));
m_Grid.SetItemText(i,1,(_bstr_t)m_pRecordset->GetCollect(_variant_t((long)1)));
m_Grid.SetItemText(i,2,(_bstr_t)m_pRecordset->GetCollect(_variant_t((long)2)));
m_Grid.SetItemText(i,3,(_bstr_t)m_pRecordset->GetCollect(_variant_t((long)3)));

*/

i++;

              //将记录集指针移动到下一条记录

              m_pRecordset->MoveNext();

       }

       //断开数据库连接

       ExitConnect();

 

}

接下来为四个edit控件和一个list constrol控件关联变量,在资源中右键点击选择classwizar里的Member variables,分别为它们设置变量为m_ID,m_Name,m_Sex,m_Culture,m_Grid.dlg类的头文件部分自动会生成

CString  m_ID;

CString  m_Name;

CString  m_Sex;

CString  m_Culture;

CListCtrl m_Grid;

 

Dlg类构造函数中

       m_ID = _T("");

       m_Name = _T("");

       m_Sex = _T("");

       m_Culture= _T("");

dlg类的DoDataExchange()函数中

DDX_Text(pDX,IDC_EDIT1, m_ID);

       DDX_Text(pDX,IDC_EDIT2, m_Name);

       DDX_Text(pDX,IDC_EDIT3, m_Sex);

       DDX_Text(pDX,IDC_EDIT4, m_Culture);

 

接下来双击那四个功能按钮和一个列表控件的点击响应功能,分别生成各自的响应函数

 

//记录数据添加功能

void CMy1Dlg::OnButton1()

{

       UpdateData(TRUE);

       if(m_ID.IsEmpty()|| m_Name.IsEmpty() || m_Sex.IsEmpty() || m_Culture.IsEmpty())

       {

              MessageBox("基础信息不能为空!");

              return;

       }

       OnInitADOConn();

       _bstr_tsql;

       sql= "select * from 表1";

       m_pRecordset.CreateInstance(__uuidof(Recordset));

       m_pRecordset->Open(sql,m_pConnection.GetInterfacePtr(),adOpenDynamic,

              adLockOptimistic,adCmdText);

       try

       {

              m_pRecordset->AddNew(); //添加新行

//两种方式均可

/*

m_pRecordset->PutCollect(_variant_t((long)0),(_bstr_t)m_ID);
m_pRecordset->PutCollect(_variant_t((long)1),(_bstr_t)m_Name);
m_pRecordset->PutCollect(_variant_t((long)2),(_bstr_t)m_Sex);
m_pRecordset->PutCollect(_variant_t((long)3),(_bstr_t)m_Culture);

              */

m_pRecordset->PutCollect("num",(_bstr_t)m_ID);

              m_pRecordset->PutCollect("name",(_bstr_t)m_Name);

              m_pRecordset->PutCollect("gender",(_bstr_t)m_Sex);

              m_pRecordset->PutCollect("dept",(_bstr_t)m_Culture);

              m_pRecordset->Update(); //更新数据表

              ExitConnect();

       }

catch(_com_error e)
{
       //AfxMessageBox(e->ErrorMessage());
MessageBox(e.Description());
        return;
}

       catch(...)

       {

              MessageBox("操作失败");

              return;

       }

       MessageBox("添加成功");

       m_Grid.DeleteAllItems();//删除列表控件

       AddToGrid();                    

}

 

//dlg类头文件声明一个long型变量,用来保存用户单击的记录在列表控件的位置为列表,该变量定义在dlg的类内。

//控件的NM_CLICK消息添加消息处理函数(即双击资源框里的listconstrol控件就会生成)

void CCMy1DlgDlg::OnNMDblclkList1(NMHDR *pNMHDR, LRESULT *pResult)
{
//LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<NMITEMACTIVATE>(pNMHDR);


LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<NMITEMACTIVATE *>(pNMHDR);
// TODO: 在此添加控件通知处理程序代码
//UpdateData(true);
//int nItem=pNMItemActivate->iItem;


// TODO: 在此添加控件通知处理程序代码
long pos = m_Grid.GetSelectionMark();
m_ID = m_Grid.GetItemText(pos,0);
m_Name = m_Grid.GetItemText(pos,1);
m_Sex = m_Grid.GetItemText(pos,2);
m_Culture = m_Grid.GetItemText(pos,3);
UpdateData(FALSE);
//*pResult = 0;


*pResult = 0;
}

//修改数据功能

void CMy1Dlg::OnButton2()

{

       UpdateData(TRUE);

       if(m_ID.IsEmpty()|| m_Name.IsEmpty() || m_Sex.IsEmpty() || m_Culture.IsEmpty())

       {

              MessageBox("基础信息不能为空!");

              return;

       }

       OnInitADOConn();

       _bstr_tsql;

       sql= "select * from stud";

       m_pRecordset.CreateInstance(__uuidof(Recordset));

       m_pRecordset->Open(sql,m_pConnection.GetInterfacePtr(),adOpenDynamic,

              adLockOptimistic,adCmdText);

       longpos = m_Grid.GetSelectionMark();

       try

       {

              m_pRecordset->Move((long)pos,vtMissing);

             

m_pRecordset->PutCollect(_variant_t((long)0),(_bstr_t)m_ID);
m_pRecordset->PutCollect(_variant_t((long)1),(_bstr_t)m_Name);
m_pRecordset->PutCollect(_variant_t((long)2),(_bstr_t)m_Sex);
m_pRecordset->PutCollect(_variant_t((long)3),(_bstr_t)m_Culture);

//两种方式均可
/*m_pRecordset->PutCollect("num",(_bstr_t)m_ID);
m_pRecordset->PutCollect("name",(_bstr_t)m_Name);
m_pRecordset->PutCollect("gender",(_bstr_t)m_Sex);
m_pRecordset->PutCollect("dept",(_bstr_t)m_Culture);*/

              m_pRecordset->Update();

              ExitConnect();

       }

       catch(...)

       {

              MessageBox("操作失败");

              return;

       }

       MessageBox("修改成功");

       m_Grid.DeleteAllItems();

       AddToGrid();      

}

//删除数据功能

void CMy1Dlg::OnButton3()

{

      

// TODO: 在此添加控件通知处理程序代码
if(MessageBox("你确定要删除吗?","DELETE",MB_ICONEXCLAMATION|MB_OKCANCEL)==IDCANCEL)

        return;


OnInitADOConn();
_bstr_t sql;
sql = "select * from stud";
m_pRecordset.CreateInstance(__uuidof(Recordset));
m_pRecordset->Open(sql,m_pConnection.GetInterfacePtr(),adOpenDynamic,
adLockOptimistic,adCmdText);
long pos = m_Grid.GetSelectionMark();
try
{
m_pRecordset->Move((long)pos,vtMissing);
m_pRecordset->Delete(adAffectCurrent);
m_pRecordset->Update();
ExitConnect();

}

catch(_com_error e)
{
MessageBox(e.Description());
return;
}

catch(...)
{
MessageBox("操作失败");
return;
}
MessageBox("删除成功");
m_Grid.DeleteAllItems();
AddToGrid();

 

}

//清除功能

void CMy1Dlg::OnButton4()

{

       m_ID= "";

       m_Name= "";

       m_Sex= "";

       m_Culture= "";

       UpdateData(FALSE); 

}