www.pudn.com > 49636961mysql_test.rar > mysql_test.cpp


// mysql_test.cpp : Defines the entry point for the console application. 
// 
 
#include "stdafx.h" 
#include "mysql_test.h" 
 
#ifdef _DEBUG 
#define new DEBUG_NEW 
#undef THIS_FILE 
static char THIS_FILE[] = __FILE__; 
#endif 
 
///////////////////////////////////////////////////////////////////////////// 
// The one and only application object 
 
CWinApp theApp; 
_ConnectionPtr	m_pConnection; 
_RecordsetPtr	m_pRecordset; 
 
using namespace std; 
 
 
BOOL Connect_MySQL_DataBase(CString& strConn); 
void Test(); 
 
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) 
{	 
	CoInitialize(NULL);	 
 
	int nRetCode = 0;	 
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) 
	{		 
		cerr << _T("Fatal Error: MFC initialization failed") << endl; 
		nRetCode = 1; 
	} 
	else 
	{ 
			 
		CString strHello; 
		strHello.LoadString(IDS_HELLO); 
		cout << (LPCTSTR)strHello << endl; 
 
		CString strConn( 
			//采用myodbc 连接mysql 
		   "Provider=MSDASQL.1;Password=zcc123;Persist Security Info=True;\ 
			User ID=root;Data Source=test"); 
		//也可以采用myole连接mysql,其测试方法下载myole后,建立一个udl文件自行连接到 
		//mysql中,test后生成字符串后替换myodbc的字符串才行(通过文本文件打开udl文件拷贝即可)。 
 
		if (Connect_MySQL_DataBase(strConn)) 
		{ 
			cout<<"test connect ok"<Open(strSql, _variant_t((IDispatch*)m_pConnection,true), 
				adOpenDynamic, adLockOptimistic, adCmdText); 
 
	while(!m_pRecordset->adoEOF) 
	{			 
		variant_t ret = m_pRecordset->GetCollect("id");					 
		int i = ret.lVal; 
		cout<MoveNext(); 
	} 
} 
 
/* 
  连接mysql数据库 
*/ 
BOOL Connect_MySQL_DataBase(CString& strConn) 
{		 
	try 
	{ 
		HRESULT hr = m_pConnection.CreateInstance(_T("ADODB.Connection")); 
		if (SUCCEEDED(hr)) 
		{ 
			m_pConnection->CursorLocation = adUseClient;			 
			m_pConnection->Open((_bstr_t)strConn, "", "", adConnectUnspecified); 
		} 
		else 
			return FALSE; 
	} 
	catch(_com_error &e) 
	{ 
		//MessageBox(e.ErrorMessage());		 
		return FALSE; 
	}	 
	return TRUE;	 
}