標籤:
對於軟體開發其實說白了就是在不停地和資料打交道, 所以資料庫的操作是必不可少的, 接下來介紹VC開發中利用ADO建立ODBC資料來源來訪問MySQL資料庫.
從我接觸的資料庫編程方式來說, 我覺得在vc開發串連資料庫是比較難的, 也是很容易出錯. 在android中, 系統內建sqlite資料庫,只需要使用SQLiteOpenHelper抽象類別即可完成與資料庫的操作. 在java中, 使用jdbc串連mysql資料庫, 下載相應jar調用相應介面,傳入資料庫類型與使用者名稱密碼進行資料庫的操作. 但是ado串連資料庫比較複雜, 接下來我們看一下如何使用ado串連資料庫.
一. 安裝mysql
首先你需要確保電腦上已經安裝了mysql資料庫, 並使用使用者名稱與密碼成功使用mysql. 如何安裝配置mysql, 這裡不做詳細介紹.
如果不瞭解如何安裝配置mysql可以參考這個地址: 點擊開啟連結
二. ADO方式串連MySql
1. 匯入ado資料庫, 在你的程式中添加下面語句來匯入ado資料庫
// no_namespace rename("EOF", "adoEOF")防止命名重複,將EOF重新命名為adoEOF#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")
2. 初始化com環境
//初始化com環境AfxOleInit();
3. 建立資料表結構,用來儲存從資料庫中擷取的內容
假設資料表只有兩個欄位:使用者ID與使用者名稱
typedef struct _OBJ_USER{int User_ID;TCHAR User_Name[32];}OBJ_USER;4.建立操作資料庫的類operator類
class CDataOperator{public:CDataOperator();~CDataOperator();public://開啟指定的資料庫BOOL OpenDatabase(CString strDbName, CString strUserName, CString strUserPwd);public://執行sql語句,增加資料,刪除資料BOOL ExecuteSQL(CString sql);//查詢資料BOOL Select_From_User(vector<OBJ_USER> &vecObjUser);//插入資料, 可以插入圖片,位元據(大資料)BOOL Insert_Into_User(OBJ_USER &objUser);//更新資料, 可更新大資料BOOL Update_For_User(OBJ_USER &objUser);public://連線物件_ConnectionPtr m_pConnection;};
5. operator類的定義
CDataOperator::CDataOperator(){try{//建立連線物件HRESULT hr = m_pConnection.CreateInstance(_T("ADODB.Connection"));if (FAILED(hr)){m_pConnection = NULL;}}catch (_com_error &e){e.ErrorMessage();}}CDataOperator::~CDataOperator(){ if (m_pConnection) { try { //將連線物件關閉 HRESULT hr = m_pConnection->Close(); } catch (_com_error &e) { e.ErrorMessage(); } //釋放連線物件 m_pConnection.Release(); m_pConnection = NULL; }}//開啟資料庫的操作BOOL CDataOperator::OpenDatabase(CString strDbName, CString strUserName, CString strUserPwd){ if (NULL == m_pConnection) { return FALSE; } if (m_pConnection) { try { CString strConnectionName; strConnectionName.Format(_T("DATABASE=%s;DSN=myodbc;OPTION=0;PWD=%s;PORT=0;SERVER=localhost;UID=%s;"), strDbName, strUserPwd, strUserName); HRESULT hr = m_pConnection->Open(_bstr_t(strConnectionName.GetBuffer(0)), _T(""), _T(""), -1); if (FAILED(hr)) { m_pConnection = NULL; } } catch (_com_error &e) { e.ErrorInfo(); return FALSE; } } return true;}
擷取連接字串的方法:
strConnectionName.Format(_T("DATABASE=%s;DSN=myodbc;OPTION=0;PWD=%s;PORT=0;SERVER=localhost;UID=%s;"), strDbName, strUserPwd, strUserName);連接字串中包含的資訊包括資料庫的類型, 資料庫的使用者名稱與密碼, 在這裡和java用jdbc串連資料庫類似, 擷取連接字串:
"DATABASE=%s;DSN=myodbc;OPTION=0;PWD=%s;PORT=0;SERVER=localhost;UID=%s;" 的方式如下:
(1) 首先需要安裝mysql-connector-odbc-3.51.26-win32.ini, 才能串連mysql資料庫
(2) 建立一個txt檔案,尾碼名改為.udl,雙擊開啟
(3) 提供者-->Microsoft OLE DB Provider for ODBC Drivers,點擊‘下一步’,選擇‘使用連接字串’,
點擊‘編譯’,選擇‘機器資料來源’,點擊‘建立’,點擊‘下一步’,選擇MYSQL(如果你安裝了第一步中的應用會有MYSQL驅動程式)點擊‘下一步’,
然後填寫相應的內容,需要串連的資料庫,server,使用者名稱,密碼等,點擊test按鈕,測試是否串連成功,串連成功,儲存。
(4) 用記事本開啟檔案就擷取到了連接字串。
6. CDataOperator類執行sql語句操作的介面
BOOL CDataOperator::ExecuteSQL(CString sql){if (NULL == m_pConnection){return FALSE;}if (m_pConnection){try{HRESULT hr = m_pConnection->Execute(_bstr_t(sql), NULL, 1);if (FAILED(hr)){m_pConnection = NULL;}}catch (_com_error &e){e.ErrorMessage();return FALSE;}}return true;}
7. 從資料庫中擷取資料
BOOL CDataOperator::Select_From_User(vector<OBJ_USER> &vecObjUser){if (NULL == m_pConnection)return FALSE;//記錄集對象_RecordsetPtr m_pRecordSet;HRESULT hr = m_pRecordSet.CreateInstance(_T("ADODB.Recordset"));if (FAILED(hr)){return FALSE;}//擷取資料前先清空vecObjUser.clear();CString strSQL = _T("select User_ID, User_Name from user");hr = m_pRecordSet->Open(_bstr_t(strSQL),m_pConnection.GetInterfacePtr(),adOpenStatic, adLockOptimistic, adCmdText);if (FAILED(hr)){m_pRecordSet.Release();return FALSE;}//擷取當前遊標的位置VARIANT_BOOL bRet = m_pRecordSet->GetadoEOF();//如果遊標在末尾返回失敗//遍曆資料while(!bRet){_variant_t varUserID = m_pRecordSet->GetCollect("User_ID");_variant_t varUserName = m_pRecordSet->GetCollect("User_Name");OBJ_USER objUser;objUser.User_ID = varUserID.intVal;_tcscpy_s(objUser.User_Name, (TCHAR*)(_bstr_t)varUserName);vecObjUser.push_back(objUser);//遊標下移m_pRecordSet->MoveNext();bRet = m_pRecordSet->GetadoEOF();}m_pRecordSet->Close();m_pRecordSet.Release();m_pRecordSet = NULL;return true;}
8. 往資料庫中插入資料(可以插入圖片,二進位大資料等)
我們通過CDataOperator::ExecuteSQL方法, 通過傳入插入sql語句可以實現往資料中插入資料, 但是插入圖片或二進位大資料這種方式並不適合.所以單獨將插入與更新操作實現,支援大資料的操作
BOOL CDataOperator::Insert_Into_User(OBJ_USER &objUser){if (NULL == m_pConnection)return FALSE;//記錄集對象_RecordsetPtr m_pRecordSet;HRESULT hr = m_pRecordSet.CreateInstance(_T("ADODB.Recordset"));if (FAILED(hr)){return FALSE;}CString strSQL = _T("select User_ID, User_Name from user");hr = m_pRecordSet->Open(_bstr_t(strSQL), m_pConnection.GetInterfacePtr(),adOpenStatic, adLockOptimistic, adCmdText);if (FAILED(hr)){m_pRecordSet.Release();return FALSE;}try{//增加一行m_pRecordSet->AddNew();}catch (_com_error &e){e.ErrorMessage();return FALSE;}try{m_pRecordSet->PutCollect(_T("User_ID"), _variant_t(objUser.User_ID));m_pRecordSet->PutCollect(_T("User_Name"), _variant_t(objUser.User_Name));}catch (_com_error &e){m_pRecordSet->Close();m_pRecordSet.Release();e.ErrorMessage();return FALSE;}m_pRecordSet->Update();m_pRecordSet->Close();m_pRecordSet.Release();m_pRecordSet = NULL;return TRUE;}
9. 更新資料庫中的資料
BOOL CDataOperator::Update_For_User(OBJ_USER &objUser){if (NULL == m_pConnection)return FALSE;//記錄集對象_RecordsetPtr m_pRecordSet;HRESULT hr = m_pRecordSet.CreateInstance(_T("ADODB.Recordset"));if (FAILED(hr)){return FALSE;}CString strSQL;strSQL.Format(_T("select User_ID, User_Name from user where User_ID=%d"), objUser.User_ID);hr = m_pRecordSet->Open(_bstr_t(strSQL), m_pConnection.GetInterfacePtr(),adOpenStatic, adLockOptimistic, adCmdText);if (FAILED(hr)){m_pRecordSet.Release();return FALSE;}try{m_pRecordSet->PutCollect(_T("User_Name"), _variant_t(objUser.User_Name));}catch (_com_error &e){m_pRecordSet->Close();m_pRecordSet.Release();e.ErrorMessage();return FALSE;}m_pRecordSet->Update();m_pRecordSet->Close();m_pRecordSet.Release();m_pRecordSet = NULL;return TRUE;}
至此, ado方式串連MySQL資料庫的步驟介紹完畢, 最難的地方我覺得是擷取連接字串和資料庫連接對象的使用. 資料庫類CDataOperator,實現了資料庫連接,
資料庫操作:增, 刪, 改, 查操作. 以後在vc開發時用到資料庫時, 使用CDataOperator可以很方便開發程式.
C++ ADO方式串連mysql資料庫