Add - Worked Example
key : purple - original code / blue - new code
Step 1 :
Within Control Panel define the Access database as a ODBC system data source.
Open Control Panel. Open ODBC Data Sources. Select System DSN. Select Add Microsoft Access Driver. Give this data source a sensible name (NamesDb) and select the correct data base from the C drive (names.mdb).
Step 2 :
Continue with the original Visual C++ application. Add the Data Source (defined above) to this project.
Select Project / Add to Project / New. Select Projects / Database Project and select a sensible name (NamesDb again?). Select Machine Data Source / NamesDb.
This will then be set to the active project within the workspace. The main project (inter) must be reselected as the active project.
Step 3 :
In the resources edit the menu bar IDR_INTERTYPE. Add a new drop down menu called Record Set. Add three options to this Add New, Update and Delete. Only the Add New feature is required for this task.
Step 4 :
Link the Add New to a AddNew() function within the View. And add the following code. The name Mr William Shakespear will be added to the database.
void
CInterView::OnAddNew()
{
_RecordsetPtr pRecordSet;
CInterDoc * pDoc;
pDoc = GetDocument();
HRESULT hr;
_bstr_t bstrQuery("SELECT * FROM Names WHERE ID IS NULL");
_variant_t vNull;
vNull.vt = VT_ERROR;
vNull.scode = DISP_E_PARAMNOTFOUND;
try
{hr = pRecordSet.CreateInstance(_uuidof(Recordset));
if (SUCCEEDED(hr))
{pRecordSet->PutRefActiveConnection(pDoc->m_pConnection);
hr = pRecordSet->Open(_variant_t(bstrQuery), vNull,
adOpenForwardOnly, adLockOptimistic, adCmdText);
if (SUCCEEDED(hr))
{AfxMessageBox("success");
// Create an array for the list of fields in
// the Products table.
COleSafeArray vaFieldlist;
vaFieldlist.CreateOneDim(VT_VARIANT,3);
// Fill in the field names now.
long lArrayIndex[1];
lArrayIndex[0] = 0;
vaFieldlist.PutElement(lArrayIndex,
&(_variant_t("SecondName")));
lArrayIndex[0] = 1;
vaFieldlist.PutElement(lArrayIndex,
&(_variant_t("Title")));
lArrayIndex[0] = 2;
vaFieldlist.PutElement(lArrayIndex,
&(_variant_t("FirstName")));
// Create an array for the list of values to go in
// the Products table.
COleSafeArray vaValuelist;
vaValuelist.CreateOneDim(VT_VARIANT,3);
// Fill in the values for each field.
lArrayIndex[0] = 0;
vaValuelist.PutElement(lArrayIndex,
&(_variant_t("Turvey")));
lArrayIndex[0] = 1;
vaValuelist.PutElement(lArrayIndex,
&(_variant_t("Mr")));
lArrayIndex[0] = 2;
vaValuelist.PutElement(lArrayIndex,
&(_variant_t("Kevin")));
pRecordSet->AddNew(vaFieldlist, vaValuelist);
pRecordSet->Close();}
}
}
catch( _com_error &e )
{TRACE( "Error:%08lx.\n", e.Error());
TRACE( "ErrorMessage:%s.\n", e.ErrorMessage());
TRACE( "Source:%s.\n", (LPCTSTR) _bstr_t(e.Source()));
TRACE( "Description:%s.\n", (LPCTSTR) _bstr_t(e.Description()));}
catch(...)
{TRACE( "\n*** Unhandled Exception ***\n" );
}
}
Click here for the basic exercise
Click here for the source code
Click here to return to menu