1 建立VC工程,添加以下头文件
#include "AtlConv.h"
#import "c:\Program Files\Common Files\System\ado\msadox.dll"
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")
#include
#pragma comment(lib, "ODBC32.lib")
2 实现代码
BOOL CheckMysql() { HRESULT hr = S_OK; BOOL bRet = TRUE; _ConnectionPtr m_pConnection; _RecordsetPtr m_pRecordset; try { // 创建Connection对象 if (!SUCCEEDED(m_pConnection.CreateInstance("ADODB.Connection") )) { MessageBoxA(NULL, "ADODB.Connection 创建失败!", "Connect String", MB_OK); } _bstr_t strConnect = "Provider=MSDASQL.1;Driver={MySQL ODBC 5.1 Driver};Password=mima;Persist Security Info=True;User ID=user;DATABASE=db;SERVER=localhost;PORT=34223"; if (SUCCEEDED(m_pConnection->Open(strConnect,"","",0))) { OutputDebugString(_T("[BillDBSvr] - Info 当前打开数据库连接成功! ")); m_pRecordset.CreateInstance(_uuidof(Recordset));//初始化Recordset指针 char szSql[512] = {0}; _bstr_t strSql= "select * from miaosha_tasks"; BSTR bstrSQL = strSql.GetBSTR(); HRESULT hrRet = m_pRecordset->Open(bstrSQL,(IDispatch*)m_pConnection,adOpenDynamic,adLockOptimistic,adCmdText); if (SUCCEEDED(hrRet)) { OutputDebugString(_T("[BillDBSvr] - Info 当前访问数据库表成功! ")); } else { OutputDebugString(_T("[BillDBSvr] - Info 当前访问数据库表失败! ")); } _variant_t value; //VARIANT数据类型 while(!m_pRecordset->adoEOF)//遍历所有记录 { value = m_pRecordset->GetCollect(0); if (value.vt != VT_NULL) { value.Clear(); } } m_pRecordset->Close(); } else { OutputDebugString(_T("[BillDBSvr] - Info 当前打开数据库连接失败! ")); } m_pConnection->Close(); } // 捕捉异常 catch(_com_error e) { // 显示错误信息 ::MessageBox(NULL, e.Description(), _T("Sql Server Error"), MB_OK); bRet = FALSE; } return bRet; }
本文介绍如何在VC工程中通过ODBC连接到MySQL数据库。首先引入相关库和头文件,然后创建ADODB.Connection对象,设置连接字符串,打开数据库连接。接着创建Recordset对象,执行SQL查询,遍历并处理查询结果。最后关闭数据库连接。
300

被折叠的 条评论
为什么被折叠?



