Hi,
I am using MFC application in visual studio 2008. Currently i am doing to connect database using ODBC in MFC application. I want to do that in code. I got a code in some of the forums. Also i verified that if you need to connect, necessary CDatabase class needed to open the connection. This is my problem. When i use the below code how can i get a CDatabase class and it is default class in VC++, how need to declare an object for this one. Please see the below code. This code is working as get a data from recordset and store in the list box. I hope your's reply.
Code:void CNetFormDoc::OpenComm() { CDatabase m_database; CString sqlString; CString sCatID,sCategory; CString sDriver ="Progress OpenEdge 10.2A Driver"; CString sFile = "d:\\works"; //CString sFile = "d:\\works\\ReadDB\\Test.mdb"; CString sDsn; //Build ODBC Connection String // Build ODBC connection string sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile); TRY { // Open the database //database.Open(NULL,false,false,sDsn); m_database.OpenEx(sDsn,0); // Allocate the recordset CRecordset recset( &m_database ); // Build the SQL statement sqlString = "SELECT CatID, Category " "FROM Categories"; // Execute the query recset.Open(CRecordset::forwardOnly,sqlString,CRecordset::readOnly); // Reset List control if there is any data ResetListControl(); //// populate Grids ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES); // Column width and heading m_ListControl.InsertColumn(0,"Category Id",LVCFMT_LEFT,-1,0); m_ListControl.InsertColumn(1,"Category",LVCFMT_LEFT,-1,1); m_ListControl.SetColumnWidth(0, 120); m_ListControl.SetColumnWidth(1, 200); // Loop through each record while( !recset.IsEOF() ) { // Copy each column into a variable recset.GetFieldValue("CatID",sCatID); recset.GetFieldValue("Category",sCategory); // Insert values into the list control iRec = m_ListControl.InsertItem(0,sCatID,0); m_ListControl.SetItemText(0,1,sCategory); // goto next record recset.MoveNext(); } Close the database database.Close(); } CATCH(CDBException, e) { // If a database exception occured, show error msg AfxMessageBox("Database error: "+e->m_strError); } END_CATCH; }



Reply With Quote