Please, I am having problems with getfieldvalue, if I use single quotes on the first arguments, it compile without errors, but it does not display database contents, at run time it gives me; Database error: Incorrect field name or field index , if I use double quotes, it does it compile.
void CehilenDBDlg::OnBnClickedButtonRetrieve(){
// TODO: Add your control notification handler code here
CDatabase database;
CString SqlString;
CString strID, strName, strAge;
CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)";
CString sDsn;
CString sFile = L"C:\users\Admin\Desktop\Homebase\Test.mdb";
// You must change above path if it's different
int iRec = 0;
// Build ODBC connection string
sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s", sDriver, sFile);
// Build ODBC connection string
TRY{
// Open the database
database.Open(NULL, false, false, sDsn);
// Allocate the recordset
CRecordset recset(&database);
// Build the SQL statement
SqlString = "SELECT ID, Fname, Age " "FROM Employees";
// Execute the query
recset.Open(CRecordset::forwardOnly, SqlString, CRecordset::readOnly);
// Reset List control if there is any data
// populate Grids
ListView_SetExtendedListViewStyle(m_ListControl, LVS_EX_GRIDLINES);
// Column width and heading
m_ListControl.InsertColumn(0, L"Emp ID", LVCFMT_LEFT, -1, 0);
m_ListControl.InsertColumn(1, L"Name", LVCFMT_LEFT, -1, 1);
m_ListControl.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1);
m_ListControl.SetColumnWidth(0, 120);
m_ListControl.SetColumnWidth(1, 200);
m_ListControl.SetColumnWidth(2, 200);
// Loop through each record
while (!recset.IsEOF()) {
// Copy each column into a variable
// if I use double quotes I get erross
// error C2664: 'void CRecordset::GetFieldValue(short,CStringA &)' : cannot convert argument 1 from 'const char [3]' to 'LPCTSTR'
//13projectsehilendbehilendbdlg.cpp(260): warning C4309: 'argument' : //truncation of constant value
recset.GetFieldValue('ID', strID);
recset.GetFieldValue('name', strName);
recset.GetFieldValue('Age', strAge);
// Insert values into the list control
iRec = m_ListControl.InsertItem(0, strID, 0);
m_ListControl.SetItemText(0, 1, strName);
m_ListControl.SetItemText(0, 2, strAge);
// goto next record
recset.MoveNext();
}
// Close the database
database.Close();
} CATCH(CDBException, e) {
// If a database exception occured, show error msg
AfxMessageBox(L"Database error: " + e->m_strError);
}
END_CATCH;
}
void CehilenDBDlg::ResetListControl(){
m_ListControl.DeleteAllItems();
int iNbrOfColumns;
CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetDlgItem(0);
if (pHeader) {
iNbrOfColumns = pHeader->GetItemCount();
}
for (int i = iNbrOfColumns; i >= 0; i--) {
m_ListControl.DeleteColumn(i);
}
}
question from:
https://stackoverflow.com/questions/65855910/how-to-retrieve-records-from-ms-access-database-file-in-mfc-using-crecordsetge 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…