Updating Records from the Employee Database

The UpdateEmpRec member function updates records from the Employee database:

void CDAOEMPDoc::UpdateEmpRec(long m_nEmpNum, LPCTSTR lpszFirstName, 
			LPCTSTR lpszHomePhone, LPCTSTR lpszLastName,	
			LPCTSTR lpszNotes, DATE HireDate)
{
	//Convert the date to a dbVariant.
	COleVariant cdbHireDate;
	cdbHireDate.date = HireDate;
	cdbHireDate.vt = VT_DATE;

	try
		{
		//The recordset must be in edit mode.
		if(m_cEmpRecordSet.GetEditMode() == dbEditNone)
			m_cEmpRecordSet.Edit();

		m_cEmpRecordSet.SetField(EMP_FIRST_NAME, COleVariant(lpszFirstName, VT_BSTRT));
		m_cEmpRecordSet.SetField(EMP_HOME_PHONE, COleVariant(lpszHomePhone, VT_BSTRT));
		m_cEmpRecordSet.SetField(EMP_LAST_NAME, COleVariant(lpszLastName, VT_BSTRT));
		m_cEmpRecordSet.SetField(EMP_NOTES, COleVariant(lpszNotes, VT_BSTRT));
		m_cEmpRecordSet.SetField(EMP_HIRE_DATE, cdbHireDate);

		//Commit the changes.
		m_cEmpRecordSet.Update();

		m_bEmptyTable = FALSE;

		//Return to the edited record.
		CdbBookmark cBookmark = m_cEmpRecordSet.GetLastModified();
		m_cEmpRecordSet.SetBookmark(cBookmark);
		}

	catch (CdbException e)
		{
		CdbLastOLEError exError;
		TCHAR szBuf[256];

		wsprintf(szBuf, _T("Error 0x%lx : %s\n"), e.m_hr, (LPCTSTR) exError.GetDescription());
		AfxMessageBox(szBuf);
		}
}

Because recordset manipulation functions live in the document, the application must pass the record’s field values from the view to the UpdateEmpRec member function. To update the values, this member function uses the dbDAO SetField method, which does not exist in Visual Basic DAO. You use the SetField method to bypass the Fields collection, resulting in more readable code and a performance gain.

In terms of data conversion, the process of updating values is the reverse of reading values: Member variables must be converted to variants. The MFC COleVariant class handles most common data type conversions. However, there is no conversion for DATE types, so the UpdateEmpRec member function uses a temporary variable (cdbHireDate) to store the resulting variant.

Note You must make sure that the recordset is in Edit mode before attempting an update. This happens by default for an added record, but Edit mode must be turned on explicitly for an existing record. This is a result of the document/view split; actions in the view must be mapped to corresponding behavior in the document. Any edits entered into the form are not updated until the user issues a menu or toolbar command, resulting in a position change in the recordset.