ODBC programming examples in Visual C ++

      Microsoft Developer Studio provides 32-bit ODBC drivers for most standard database format. These standard data formats including: SQL Server, Access, Paradox, dBase, FoxPro, Excel, Oracle, and Microsoft Text. If the user wishes to use other data formats, the need to install the ODBC driver and DBMS.   

      After the user to use their own DBMS database management function to generate a new database schema, you can log data source using ODBC. For the user's application, as long as the driver is installed, you can register many different databases. For details see Logging database online help about ODBC.   

      A, ODBC database classes provided by MFC   
      of Visual C ++ MFC base class library defines several database class. When using ODBC programming often use to the CDatabase (database type), the CRecordSet (recordset class) and CRecordView (visual record set class).   
      CDatabase class object provides the connection to the data source, the data source can be operated by it.   
      Class CRecordSet object provides the extracted record set from the data source. CRecordSet object is typically used in two forms: a dynamic set of rows (Dynasets) and snapshot set (snapshots). Change the dynamic line set to keep pace with other users can do, then set the snapshot is a static view of the data. Each form set is opened at the time of recording a set of records are provided, except that, when set in a row in the dynamic scroll to a recording, the recording made by other users or applications other set of the recording changes accordingly displayed.   
      CRecordView class object database records can be displayed in the form of control, this view is directly connected to a CRecordSet object table view.   

      Second, the application ODBC programming
      
application of Visual C ++ AppWizard can automatically generate an ODBC application framework, the steps are: Open the File menu, New option, select Projects, fill in the project name, select MFC AppWizard (exe), then follow the prompts AppWizard be operating.   
      When asked if AppWizard include database support, if you want to read and write the database, select Database view with file support; if you want to access information in the database without write back changes made, then select Database view without file support. After selecting database support, Database Source button is activated, select it to call Data Options dialog box. Will show the ODBC database resource has been registered in the Database Options dialog box, select the database to operate, such as: Super_ES, Select Database Tables dialog box appears after clicking OK, which lists all the selected database table included; after selecting the table to operate, and click OK. After selecting the database and data table, you can continue AppWizard operate as usual.   
      Of particular note is that: in the generated application framework View (such as: CSuper_ESView), the object contains a pointer pointing to CSuper_ESSet m_pSet, the pointer is set up by the AppWizard, the aim to establish a link between the set and the recording visual form, such that centralized record of the query results can be easily displayed on the visual form.   
      To establish contact with the data source program, required CDateBase :: OpenEx () or CDatabase :: Open () function is to initialize. Database object must be initialized before it is constructed using the record set object.

      Third, the example
  1. Search record
  query records use CRecordSet :: Open () and CRecordSet :: Requery () member function. Before using an object class CRecordSet must use CRecordSet :: Open () function to obtain a valid set of records. Once you have used CRecordSet :: Open () function, you can use the query again CRecordSet :: Requery () function.
  In calling CRecordSet :: Open () function when, if one is already open CDatabase object pointer passed to CRecordSet class object m_pDatabase member variables, then use the database object establish an ODBC connection; otherwise, if m_pDatabase is a null pointer, to create a CDatabase class object, and it is connected to the default data source, and then initialize the class CRecordSet object. The default data source is GetDefaultConnect () function is obtained. Can also provide the required SQL statement, and with it to call CRecordSet :: Open () function, for example: Super_ESSet.Open (AFX_DATABASE_USE_DEFAULT, strSQL);
  if no parameters are specified, the program uses the default SQL statement, that in GetDefaultSQL () function specified in the SQL statement to operate:

  CString CSuper_ESSet::GetDefaultSQL()
  {return _T(″[BsicData],[MinSize]″);}

  For the GetDefaultSQL () function returns the name of the table, corresponding to the default operation of a SELECT statement, namely:

  SELECT *FROM BasicData,MainSize

  In the inquiry process, you can also use the member variables m_strFilter and m_strSort CRecordSet conditions to perform queries and sort the results. m_strFilter to filter string storage conditions after the SQL statement WHERE string; m_strSort to sort strings, the string stored in the SQL statement ORDER BY. Such as:

  Super_ESSet.m_strFilter = "type ="电动机' "; 
  Super_ESSet.m_strSort = "voltage";
  Super_ESSet.Requery ();

  Corresponding SQL statement is:

  SELECT *FROM BasicData,MainSize
  WHERE TYPE=‘电动机’
  ORDER BY VOLTAGE

  In addition to the direct assignment to m_strFilter, you can also use parameterized. Parameterization can use more intuitive and easier to complete the query task conditions. The step of using a parameterized as follows:
  S parametric statement:

  CString p1;
  float p2;

  S in the constructor initializes a variable parameter:

  p1=_T(″″);
  p2=0.0f;
  m_nParams=2;

  The corresponding parametric S column binding:

  pFX->SetFieldType(CFieldExchange::param)
  RFX_Text(pFX,_T(″P1″),p1);
  RFX_Single(pFX,_T(″P2″),p2);

  After the completion of the above steps may be carried out using a parametric query conditions:

  m_pSet->m_strFilter=″TYPE=? AND VOLTAGE=?″;m_pSet->p1=″电动机″;
  m_pSet->p2=60.0;
  m_pSet->Requery();

  The value of the variable parameter to replace the query string "?" Wildcard in the order binding.
  If the result of the query is a plurality of records, can function Move CRecordSet class (), MoveNext (), MovePrev (), MoveFirst () and the MoveLast () to move the cursor.
  2. Add record
  increase recorded using AddNew () function, the requirements must be based database allowing increased Open:

  m_pSet-> AddNew (); // add a new record at the end of the table
  m_pSet-> SetFieldNull (& (m_pSet-> m_type), FALSE);
  m_pSet-> m_type = "motor";
  ......
  // enter the new field value
  m_pSet-> Update ();
  // new records into a database
  m_pSet-> Requery ();
  // rebuild record set

  3. Delete records
  can be used directly Delete () function to delete records, and call Delete () do not need to call Update () function after the function:

  m_pSet->Delete();
  if (!m_pSet->IsEOF())
  m_pSet->MoveNext();
  else
  m_pSet->MoveLast();

  4. Modify Record
  Review recording using the Edit () function:

  m_pSet-> the Edit ();
  // modify the current record
  m_pSet-> m_type = "generator";
  // modify the current record field value
   ......
   m_pSet-> the Update (); // will modify the results into the database
  m_pSet-> Requery ();

  The undo operation is
  desired to abandon the current operation if the user selects to add or modify records may be called before the Update () function:
  the CRecordSet :: the Move (AFX_MOVE_REFRESH) to modify or undo the increase mode, and restore or modify the pattern before adding the current record. Wherein the value of the parameter is zero AFX_MOVE_REFRESH.
  6. Database multiplexed connections
  defined in a member variable m_pDatabase class CRecordSet:

  CDatabase* m_pDatabase;

  It is a pointer to the class object database. If the object class CRecordSet the call Open () function before, it has been opened to a class object pointer passed m_pDatabase CDatabase, can share the same CDatabase class object. Such as:

  CDatabase m_db;
  CRecordSet m_set1,m_set2;
  m_db.Open(_T(″Super_ES″)); //建立ODBC连接
  m_set1.m_pDatabase=&m_db;
  //m_set1复用m_db对象
  m_set2.m_pDatabse=&m_db;
  // m_set2复用m_db对象

  7.SQL语句的直接执行
  虽然我们可以通过CRecordSet类完成大多数的查询操作,而且在CRecordSet::Open()函数中也可以提供SQL语句,但是有时候我们还是希望进行一些其他操作,例如建立新表、删除表、建立新的字段等,这时就需要使用CDatabase类直接执行SQL语句的机制。通过调用CDatabase::ExecuteSQL()函数来完成SQL语句的直接执行:

  BOOL CDB::ExecuteSQLAndReportFailure(const CString& strSQL)
  {TRY
  {m_pdb->ExecuteSQL(strSQL);
  //直接执行SQL语句}
  CATCH (CDBException,e)
  {CString strMsg;
  strMsg.LoadString(IDS_EXECUTE_SQL_FAILED);
  strMsg+=strSQL;
  return FALSE;}
   END_CATCH
  return TRUE;}

  应当指出的是,由于不同的DBMS提供的数据操作语句不尽相同,直接执行SQL语句可能会破坏软件的DBMS无关性,因此在应用中应当慎用此类操作。
  8.动态连接表
  表的动态连接可以利用在调用CRecordSet::Open()函数时指定SQL语句来实现。同一个记录集对象只能访问具有相同结构的表,否则查询结果将无法与变量相对应。

void CDB::ChangeTable()
{  
if (m_pSet->IsOpen()) m_pSet->Close();
 switch (m_id)
 {
  case 0: 
   m_pSet->Open(AFX_DB_USE_DEFAULT_TYPE,″SELECT * FROM SLOT0″);
   //连接表SLOT0
   m_id=1; 
   break;
  case 1: 
   m_pSet->Open(AFX_DB_USE_DEFAULT_TYPE,″SELECT * FROM SLOT1″); //连接表SLOT1
   m_id=0;
   break;
 }
}

  9.动态连接数据库
  可以通过赋与CRecordSet类对象参数m_pDatabase来连接不同数据库的CDatabase对象指针,从而实现动态连接数据库。

void CDB::ChangeConnect()
{
 CDatabase* pdb=m_pSet->m_pDatabase;
 pdb->Close();
 switch (m_id)
 {   
case 0:
   if (!pdb->Open(_T(″Super_ES″)))
    //连接数据源Super_ES
   {
    AfxMessageBox(″数据源Super_ES打开失败″,″请检查相应的ODBC连接″, MB_OK|MB_ICONWARNING);
    exit(0);
   }
   m_id=1;
   break; 
    case 1:
   if (!pdb->Open(_T(″Motor″)))
   //连接数据源Motor
   {
    AfxMessageBox(″数据源Motor打开失败″,″请检查相应的ODBC连接″, MB_OK|MB_ICONWARNING);
    exit(0);
   }
   m_id=0; 
   break;
 }
}

  总结:
  Visual C++中的ODBC类库可以帮助程序员完成绝大多数的数据库操作。利用ODBC技术使得程序员从具体的DBMS中解脱出来,从而可以减少软件开发的工作量,缩短开发周期,并提高效率和软件的可靠性。

发布了1 篇原创文章 · 获赞 0 · 访问量 2715

Guess you like

Origin blog.csdn.net/yjj350418592/article/details/105127058