There are several ways to connect to the database:
- SQL SERVER
- ODBC
- OLE DB
- MYSQL
I. MySQL
How to connect mysql database is introduced here. MySQL workbench version 6.3 is used. Other versions are also available. Installation process is Baidu
1. Table definition
Development platform
The vs2008 version is used here. It is recommended to use the 2010 version. You can also use Visual C + + to import according to the situation.
Interface:
Code
A CDatabase class is defined to encapsulate database operations.
See the source code for mysql.h and other database files.
#include "StdAfx.h" #include "MFCDlg.h" #include <cstring> #include <string> #include "CDatabase.h" // Constructor initializes MYSQL object CDatabase::CDatabase() { mysql_init(&mysql); } // Destructor CDatabase::~CDatabase() { Close(); mysql_library_end(); } // Close database connection void CDatabase::Close() { if(query) mysql_free_result(query); mysql_close(&mysql); } // Open database bool CDatabase::Open(char* host, char* user, char* pass, char* db) { CString error; if(!mysql_real_connect(&mysql, host, user, pass, db, 3306, NULL, 0)) { error = mysql_error(&mysql); AfxMessageBox(error); //printf("failed to perform query operation. Error reason:% s \ n ", MySQL" & error "; return false; } return true; } //Selection record bool CDatabase::Execute(char* sql) { if(mysql_real_query(&mysql, sql, strlen(sql))) return false; query = mysql_use_result(&mysql); return true; } //Set encoding void CDatabase::SetCode() { //mysql_set_character_set(&mysql, "utf8"); AfxMessageBox("Success"); } //Get the number of fields int CDatabase::GetFieldNum() { if (query) return mysql_num_fields(query); return 0; } //Get record lines MYSQL_ROW CDatabase::GetRecord() { if (query) { row = mysql_fetch_row(query); return row; } return NULL; } // Get Recordset void CDatabase::GetRecords() { query = mysql_use_result(&mysql); } // Get the length of the recordset field value unsigned long * CDatabase::GetRecordFieldLength() { if (query) return mysql_fetch_lengths(query); return NULL; } // Show query result set bool CDatabase::ShowRecords(char* sql) { // Perform query operation if (!Execute(sql)) return FALSE; unsigned int nFields = GetFieldNum(); CEdit* pWnd = (CEdit*)AfxGetApp()->m_pMainWnd->GetDlgItem(IDC_EDIT1); while ((row = GetRecord())) { unsigned long *lengths; lengths = GetRecordFieldLength(); for(UINT i = 0; i < nFields; i++) { //printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL"); char *s = new char[200]; sprintf(s,"%.*s ", (int) lengths[i], row[i] ? row[i] : "NULL"); //CMFCDlg myDialog = new CMFCDlg(); //((CEdit*)myDialog.GetDlgItem(IDC_EDIT1))->SetWindowText(_T("xxxx")); //myDialog->SetWindowText("123") int nLength=pWnd->SendMessage(WM_GETTEXTLENGTH); pWnd->SetSel(nLength, nLength); pWnd->ReplaceSel(s); /*m.setedit(s);*/ } //printf("\n"); } //printf("--------------------------------------------------\n"); return TRUE; }
Source link