MFC - 数据库类

MFC - 数据库类 首页 / MFC入门教程 / MFC - 数据库类

数据库是一组信息,这些信息经过组织,以便可以轻松地对其进行访问,管理和更新,基于ODBC的MFC数据库类旨在提供对任何具有ODBC驱动程序的数据库的访问,因为这些类使用ODBC,所以您的应用程序可以访问许多不同数据格式和不同本地/远程配置的数据。

您不必编写特殊情况的代码即可处理不同的数据库管理系统(DBMS),只要您的用户具有要访问的数据的适当的ODBC驱动程序,他们就可以使用您的程序来操作存储在该表中的数据,数据源是某些数据库管理系统(DBMS)托管的数据的特定,示例包括Microsoft SQL Server,Microsoft Access等。

CDatabase

MFC提供了一个CDatabase类,该类表示与数据源的连接,您可以通过该类在数据源上进行操作。

让无涯教程通过创建一个新的基于MFC对话框的应用程序来研究一个简单的示例。

步骤1 - 将TODO行的标题更改为从数据库检索数据,并拖动一个按钮和一个List控件,如以下快照所示。

Retrieve Data From DB

步骤2 - 为按钮添加单击事件处理程序,为列表控件添加控制变量m_ListControl。

步骤3 - 有一个简单的数据库,其中包含一个雇员表和一些记录,如以下快照所示。

Employees Table

步骤4 - 无涯教程需要包括以下头文件,以便可以使用CDatabase类。

#include "odbcinst.h"
#include "afxdb.h"

写入数据

SQL INSERT INTO语句用于将新的数据行添加到数据库中的表。

步骤1- 要添加新记录,将使用CDatabase类的ExecuteSQL()函数,如以下代码所示。

CDatabase database;
CString SqlString;
CString strID, strName, strAge;
CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)";
CString sDsn;
CString sFile = L"D:\\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);
TRY {
   //Open the database
   database.Open(NULL,false,false,sDsn);

   SqlString = "INSERT INTO Employees (ID,Name,age) VALUES (5,'Sanjay',69)";
   database.ExecuteSQL(SqlString);
   //Close the database
   database.Close();
}CATCH(CDBException, e) {
   //If a database exception occured, show error msg
   AfxMessageBox(L"Database error: " + em_strError);
}
END_CATCH;

步骤2 - 编译并执行上述代码后,您将看到在数据库中添加了一条新记录。

Insert Queue

查询数据

为了在MFC应用程序中检索上表,在按钮事件处理程序中实现了与数据库相关的操作,如以下步骤所示。

步骤1 - 要使用CDatabase,请构造一个CDatabase对象并调用其Open()函数。这将打开连接。

步骤2 - 构造CRecordset对象以在连接的数据源上进行操作,将记录集构造函数的指针传递给CDatabase对象。

链接:https://www.learnfk.comhttps://www.learnfk.com/mfc/mfc-database-classes.html

来源:LearnFk无涯教程网

步骤3 - 使用连接后,调用Close函数并销毁CDatabase对象。

void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() {
   //TODO: Add your control notification handler code here
   CDatabase database;
   CString SqlString;
   CString strID, strName, strAge;
   CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
   CString sFile = L"D:\\Test.mdb";
   //You must change above path if it's different
   int iRec = 0;

   //Build ODBC connection string
   sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile);
   TRY {
      //Open the database
      database.Open(NULL,false,false,sDsn);

      //Allocate the recordset
      CRecordset recset( &database );

      //Build the SQL statement
      SqlString = "SELECT ID, Name, Age " "FROM Employees";

      //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,"Emp ID",LVCFMT_LEFT,-1,0);
      m_ListControl.InsertColumn(1,"Name",LVCFMT_LEFT,-1,1);
      m_ListControl.InsertColumn(2, "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
         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("Database error: "+em_strError);
   }
   END_CATCH; 
}

//Reset List control
void CMFCDatabaseDemoDlg::ResetListControl() {
   m_ListControl.DeleteAllItems();
   int iNbrOfColumns;
   CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetDlgItem(0);
   if (pHeader) {
      iNbrOfColumns = pHeaderGetItemCount();
   }
   for (int i = iNbrOfColumns; i >= 0; i--) {
      m_ListControl.DeleteColumn(i);
   }
}

步骤4 - 这是头文件。

// MFCDatabaseDemoDlg.h : header file
//

#pragma once
#include "afxcmn.h"


// CMFCDatabaseDemoDlg dialog
class CMFCDatabaseDemoDlg : public CDialogEx {
   // Construction
   public:
      CMFCDatabaseDemoDlg(CWnd* pParent = NULL);    // standard constructor

   // Dialog Data
   #ifdef AFX_DESIGN_TIME
      enum { IDD = IDD_MFCDATABASEDEMO_DIALOG };
   #endif

   protected:
      virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
      void ResetListControl();

   // Implementation
   protected:
      HICON m_hIcon;

      // Generated message map functions
      virtual BOOL OnInitDialog();
      afx_msg void OnPaint();
      afx_msg HCURSOR OnQueryDragIcon();
      DECLARE_MESSAGE_MAP()
   public:
      CListCtrl m_ListControl;
      afx_msg void OnBnClickedButtonRead();
};

步骤5 - 编译并执行上述代码后,您将看到以下输出。

检索记录

步骤6 - 按下"Read"按钮以执行数据库操作。它将检索雇员表。

无涯教程网

检索记录

更新数据

SQL UPDATE查询用于修改表中的现有记录。您可以将WHERE子句与UPDATE查询一起使用以更新选定的行,否则所有行都将受到影响。

步骤1 - 让无涯教程通过更新ID等于5的Age来研究一个简单的示例。

SqlString = L"UPDATE Employees SET Age=59 WHERE ID=5;";
database.ExecuteSQL(SqlString);

步骤2 - 这是按钮单击事件的完整代码。

void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() {
   // 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\\Muhammad.Waqas\\Downloads\\Compressed\\ReadDB_demo\\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);
   TRY {
      // Open the database
      database.Open(NULL,false,false,sDsn);

      // Allocate the recordset
      CRecordset recset(&database);

      SqlString = L"UPDATE Employees SET Age = 59 WHERE ID = 5;";

      database.ExecuteSQL(SqlString);

      SqlString = "SELECT ID, Name, Age FROM Employees";

      // Build the SQL statement
      SqlString = "SELECT ID, Name, Age FROM Employees";

      // Execute the query
      recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);

      // Reset List control if there is any data
      ResetListControl();
      // populate Grids
      ListView_SetExtendedListViewStyle(m_listCtrl,LVS_EX_GRIDLINES);

      // Column width and heading
      m_listCtrl.InsertColumn(0,L"Emp ID",LVCFMT_LEFT,-1,0);
      m_listCtrl.InsertColumn(1,L"Name",LVCFMT_LEFT,-1,1);
      m_listCtrl.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1);
      m_listCtrl.SetColumnWidth(0, 120);
      m_listCtrl.SetColumnWidth(1, 200);
      m_listCtrl.SetColumnWidth(2, 200);

      // Loop through each record
      while (!recset.IsEOF()) {
         // Copy each column into a variable
         recset.GetFieldValue(L"ID",strID);
         recset.GetFieldValue(L"Name",strName);
         recset.GetFieldValue(L"Age", strAge);

         // Insert values into the list control
         iRec = m_listCtrl.InsertItem(0,strID,0);
         m_listCtrl.SetItemText(0,1,strName);
         m_listCtrl.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;
}

步骤3 - 编译并执行上述代码后,您将看到以下输出。

检索记录

步骤4 - 按下"Read"按钮以执行数据库操作。它将检索以下Employees表。

更新记录

步骤

删除数据

在SQL删除查询被用来从表中删除现有记录。您可以使用WHERE子句与DELETE查询删除选定行,否则,所有的记录将被删除。

步骤1 - 看一个简单的示例,删除ID等于3的记录。

SqlString = L"DELETE FROM Employees WHERE ID=3;";

database.ExecuteSQL(SqlString);

步骤2 - 这是按钮单击事件的完整代码。

void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() {
   // 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\\Muhammad.Waqas\\Downloads\\Compressed\\ReadDB_demo\\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);
   TRY {
      // Open the database
      database.Open(NULL,false,false,sDsn);

      // Allocate the recordset
      CRecordset recset(&database);

      SqlString = L"DELETE FROM Employees WHERE ID = 3;";

      database.ExecuteSQL(SqlString);

      SqlString = "SELECT ID, Name, Age FROM Employees";

      // Build the SQL statement
      SqlString = "SELECT ID, Name, Age FROM Employees";

      // Execute the query
      recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);

      // Reset List control if there is any data
      ResetListControl();
      // populate Grids
      ListView_SetExtendedListViewStyle(m_listCtrl,LVS_EX_GRIDLINES);
      // Column width and heading
      m_listCtrl.InsertColumn(0,L"Emp ID",LVCFMT_LEFT,-1,0);
      m_listCtrl.InsertColumn(1,L"Name",LVCFMT_LEFT,-1,1);
      m_listCtrl.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1);
      m_listCtrl.SetColumnWidth(0, 120);
      m_listCtrl.SetColumnWidth(1, 200);
      m_listCtrl.SetColumnWidth(2, 200);

      // Loop through each record
      while (!recset.IsEOF()) {
         // Copy each column into a variable
         recset.GetFieldValue(L"ID",strID);
         recset.GetFieldValue(L"Name",strName);
         recset.GetFieldValue(L"Age", strAge);

         // Insert values into the list control
         iRec = m_listCtrl.InsertItem(0,strID,0);
         m_listCtrl.SetItemText(0,1,strName);
         m_listCtrl.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;
}

步骤3 - 编译并执行上述代码后,您将看到以下输出。

检索记录

步骤4 - 按下"Read"按钮以执行数据库操作。它将检索雇员表。

更新记录

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

AI技术内参 -〔洪亮劼〕

从0开始学游戏开发 -〔蔡能〕

现代C++编程实战 -〔吴咏炜〕

性能测试实战30讲 -〔高楼〕

接口测试入门课 -〔陈磊〕

郭东白的架构课 -〔郭东白〕

李智慧 · 高并发架构实战课 -〔李智慧〕

零基础学Python(2023版) -〔尹会生〕

B端产品经理入门课 -〔董小圣〕

好记忆不如烂笔头。留下您的足迹吧 :)