BaluS
BaluS

Reputation: 55

Database connection from MFC application

I am a complete beginner in MFC. Just for practice I have created a dialog-box which consist of a combo box, 2 editboxes and a button. Now I want to connect to database when I click the button from my dialog-box so that the data that is entered in the combo box and editboxes will be stored in a database table. Can anyone tell how to do this?

Upvotes: 0

Views: 2392

Answers (1)

Andrew Komiagin
Andrew Komiagin

Reputation: 6556

There are several classes in MFC to work with database including CDatabase and CRecordset. So called Data Source Name (DSN) is used to access the database. Here is the sample code that stores data to ODBC-compliant DB:

  CString sID;
  m_EditBox.GetWindowText(sID);
  int nID = _ttoi(sID);

  CString sName;
  m_ComboBox.GetWindowText(sName);

  CDatabase db;

  try
  {
     db.OpenEx(_T("DSN=MYDSN"), CDatabase::noOdbcDialog);
     CString sSQL;
     sSQL.Format(_T("insert into mytable (ID, NAME) values(%d, '%s')"), nID, sName); 
     db.ExecuteSQL(sSQL);
  }
  catch(CDBException* pEx)
  {
     pEx->ReportError();
     pEx->Delete();
  }
  db.Close();

Upvotes: 1

Related Questions