3.8.1 设计员工模块(2)
(6) 双击"添加"按钮添加消息响应函数,该函数把员工信息添加到数据库中。OnBtnAdd( )代码参考如下:
- void CEmpAddDlg::OnBtnAdd()
- {
- UpdateData(); //更新数据
- if(m_strName == "") //条件判断
- {
- MessageBox("姓名不能为空!");
- return ;
- }
- if(m_nAge == 0)
- {
- MessageBox("请设置年龄!");
- return ;
- }
- CString strSex, strDepart, strBirth, strAge;
//定义字符串变量 - strBirth.Format("%d-%d-%d",m_Birth.GetYear(),
m_Birth.GetMonth(),m_Birth.GetDay()); -
- //获取时间
- int nIndex = m_SexCtrl.GetCurSel();
//获取列表框选中索引 - m_SexCtrl.GetLBText(nIndex, strSex);
//获取列表框的文本 - nIndex = m_DepartCtrl.GetCurSel();
- m_DepartCtrl.GetLBText(nIndex, strDepart);
- strAge.Format("%d", m_nAge);
//年龄数据类型转换 - m_pRecordset->AddNew;
//添加记录 - m_pRecordset->PutCollect("name",_variant_t
(m_strName)); //添加姓名 - m_pRecordset->PutCollect("age",_variant_t(
(long)m_nAge)); //添加年龄 - m_pRecordset->PutCollect("sex",_variant_t
(strSex)); //添加性别 - m_pRecordset->PutCollect("addr",_variant_t
(m_strAddr)); //添加住址 - m_pRecordset->PutCollect("depart",_variant_t
(strDepart)); //添加院系 - m_pRecordset->PutCollect("birth",_variant_t
(strBirth)); //添加生日 - m_pRecordset->PutCollect("phone",_variant_t
(m_strPhone)); //添加电话 - m_pRecordset->PutCollect("more",_variant_t
(m_strMore)); //添加备注 - char *pBuf = m_pBMPBuffer;
- VARIANT varBLOB;
- SAFEARRAY *psa;
- SAFEARRAYBOUND rgsabound[1];
- if(pBuf)
- {
- rgsabound[0].lLbound = 0;
- rgsabound[0].cElements = m_nFileLen;
- psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
- for (long i = 0; i < (long)m_nFileLen; i++)
- SafeArrayPutElement (psa, &i, pBuf++);
- varBLOB.vt = VT_ARRAY | VT_UI1;
- varBLOB.parray = psa;
- m_pRecordset->GetFields()->GetItem("photo")
->AppendChunk(varBLOB); - //保存图片数据
- }
- m_pRecordset->Update();
//更新记录集 - MessageBox("保存成功!");
- }
通过上述代码,借助Format( )函数将年月日的信息格式化到字符串中,通过AddNew( )添加一条新的记录,函数PutCollect( )将数据添加到对应的字段中。究竟是如何把图片保存到数据库中去呢?我是把jpg格式的图片以二进制数据形式存储在SQL Server 2005数据库 image字段中,并实现了可以读取数据库中字段数据显示在picture控件上。下面是具体的实现流程。
① 设定image字段:在SQL Server 2005中建立一个可以存储二进制数据的字段photo,对应数据类型应该选image。
② 保存BLOB数据:BLOB类型的数据无法用普通的方式进行存储,需要使用AppendChunk( )函数。AppendChunk( )包含在Field对象中,原型为HRESULT AppendChunk (const _variant_t & Data )。从函数原型中可以看到,关键的问题是要把二进制数据赋值给VARIANT类型的变量。关键代码如下:
- m_pRecordset->GetFields()->GetItem("photo")->AppendChunk(varBLOB);
- //BLOB数据的保存
③ 读取BLOB数据:对应于保存数据时所使用的AppendChunk( )函数,读取数据应该使用GetChunk( )函数,GetChunk( )的原型为_variant_t GetChunk(long Length)。给出数据的长度后,GetChunk( )将返回包含数据的VARIANT类型变量,然后利用SafeArrayAccessData( )函数得到VARIANT变量中指向数据的char*类型的指针,以方便处理。关键代码如下:
- long lDataSize = m_pRecordset->GetFields()->
GetItem("photo")->ActualSize; - //数据大小获取
- varBLOB=m_pRecordset->GetFields()->GetItem
("photo")->GetChunk(lDataSize); - //BLOB数据的读取
2. 删除员工信息
删除员工信息即删除系统内某员工的信息,具体实现流程如下。
(1) 添加一个对话框资源ID为IDD_EMPINFO_MANAGE_DLG,添加如图3-8所示的控件。
|
| 图3-8 删除员工信息 |