UINT CSplash::ConnectData(LPVOID ps) { AfxOleInit(); //初始化COM库 if(FAILED(HospitalConnect.CreateInstance(__uuidof(Connection)))) { ((CSplash *)ps)->ConnectFlag=true; ((CSplash *)ps)->timer_count=3; //连接COM失败标志 ((CSplash *)ps)->SendMessage(WM_CLOSE,0,0); return 0; } try{ HospitalConnect->Open(_bstr_t(theApp.strConn),"","",adModeUnknown); ((CSplash *)ps)->ConnectFlag=true; ((CSplash *)ps)->timer_count=1; //连接成功标志 ((CSplash *)ps)->SendMessage(WM_CLOSE,0,0); return 1; } catch(_com_error e) { ((CSplash *)ps)->ConnectFlag=true; //作为进度条线程停止标志 ((CSplash *)ps)->timer_count=2; //连接失败标志 ((CSplash *)ps)->SendMessage(WM_CLOSE,0,0); return 2; } }
bool RxADO::SetConnection(CString LinkString) { ::CoInitialize(NULL); cnn=NULL; cnn.CreateInstance(__uuidof(Connection)); cnn->ConnectionString=(_bstr_t)LinkString; try{ cnn->Open(L"",L"",L"",adCmdUnspecified); } catch(_com_error& e) { ErrorsPtr pErrors=cnn->GetErrors(); if (pErrors->GetCount()==0) { CString ErrMsg=e.ErrorMessage(); MessageBox(NULL,"·¢Éú´íÎó:\n\n"+ErrMsg,"ϵͳÌáʾ",MB_OK|MB_ICONEXCLAMATION); return false; } else { for (int i=0;i<pErrors->GetCount();i++) { _bstr_t desc=pErrors->GetItem((long)i)->GetDescription(); MessageBox(NULL,"·¢Éú´íÎó:\n\n"+desc,"ϵͳÌáʾ",MB_OK|MB_ICONEXCLAMATION); return false; } } } return true; }
DWORD CNHSQLServerDBO::OpenDB(_ConnectionPtr &pConnection, const wchar_t *const pwchDataSource, const wchar_t *const pwchInitialCatalog, const wchar_t *const pwchUserID, const wchar_t *const pwchPassword) { assert(NULL != pwchDataSource); assert(NULL != pwchInitialCatalog); assert(NULL != pwchUserID); assert(NULL != pwchPassword); DWORD dwReturn(0x00); wchar_t wchSql[MAX_PATH]; ZeroMemory(wchSql, sizeof(wchSql)); // 加载COM组件 CoInitialize(NULL); try { _snwprintf_s(wchSql, _countof(wchSql), _TRUNCATE, L"Provider=SQLOLEDB; Data Source=%s; Initial Catalog=%s; User ID=%s; Password=%s;", pwchDataSource, pwchInitialCatalog, pwchUserID, pwchPassword); pConnection.CreateInstance(L"ADODB.Connection"); //pConnection->ConnectionTimeout = 5; //pConnection->CommandTimeout = 5; pConnection->Open((_bstr_t)wchSql, L"", L"", adModeUnknown); } catch (_com_error &e) { //#ifdef _DEBUG const int nErrMsgLength(MAX_PATH); wchar_t *pwchErrMsg = new wchar_t[nErrMsgLength](); _snwprintf_s(pwchErrMsg, nErrMsgLength, _TRUNCATE, L"CNHSQLServerDBO::OpenDB发生错误(执行%s)。", wchSql); // 输出错误信息到输出窗口 OutputDebugStringW(L"\t"); OutputDebugStringW(pwchErrMsg); OutputDebugStringW(L"\n"); // 输出错误信息到日志文件 if (0 != wcscmp(m_wchLogFilePath, L"")) { // 当日志文件路径不为空时,写日志 CNHLogAPI::WriteLogEx(m_wchLogFilePath, LOG_ERR, L"NHSQLServerDBO", pwchErrMsg); } if (NULL != pwchErrMsg) { delete[] pwchErrMsg; pwchErrMsg = NULL; } OutputDBErrMsg(e); //#endif dwReturn = 0x01; } return dwReturn; }
// //封闭ADO类,方便以后使用 void ADOConn::OnInitADOConn(void) { ::CoInitialize(NULL); try { //创建connection对象 m_pConnection.CreateInstance("ADODB.Connection"); //设置连接字符串 _bstr_t strConnect="uid=;pwd=;DRIVER={Microsoft Access Driver (*.mdb)};DBQ=Grades.mdb;"; //SERVER和UID,PWD的设置根据实际情况来设置" /*m_pConnection->Open(strConnect,_T("admin"),_T("owenyang"),adModeUnknown);*/ m_pConnection->Open(strConnect,"admin","owenyang",adModeUnknown); } catch (_com_error e) { //显示错误信息 AfxMessageBox(e.Description()); } }
//连接SQL void Connect() { try{ ::CoInitialize(NULL); //初始化COM环境 m_pConnection.CreateInstance(__uuidof(Connection)); //创建连接对象 //通过DSN数据源对任何支持ODBC的数据库进行连接 //m_pConnection->ConnectionString="Provider=SQLOLEDB.1; Persist Security Info=True; User ID=sa; Password=a1!; Initial Catalog=InTouch; Data Source=WIN-P6OLLUM9PDM"; //请将数据库相应ID与Password更改 //不通过DSN对SQL SERVER数据库进行连接 m_pConnection->ConnectionString="driver={SQL Server};Server=127.0.0.1;DATABASE=InTouch;UID=sa;PWD=a1!"; //连接服务器和数据库 HRESULT hr=m_pConnection->Open("", "", "", 0); if(hr!=S_OK) cout<<"Can not connect to the specified database!"<<endl; } catch(_com_error e){ cout<<e.Description()<<endl; } }
bool SqlServer::connect(connection_info const& info) { # ifdef _FREETDS RETCODE sta; LOGINREC* login = dblogin(); sta = DBSETLUSER(login, info.user.c_str()); if (sta == FAIL) return false; sta = DBSETLPWD(login, info.passwd.c_str()); if (sta == FAIL) return false; DBPROCESS* proc = dbopen(login, info.url.c_str()); if (proc == NULL) return false; sta = dbuse(proc, info.database.c_str()); if (sta == FAIL) return false; d_ptr->proc = proc; # endif # ifdef _MSSQL _ConnectionPtr conn; HRESULT sta = conn.CreateInstance(__uuidof(Connection)); if (FAILED(sta)) { MessageBox(NULL, _W("failed to instance a new connection."), NULL, MB_OK); return false; } core::stringstream ss; ss << "Driver={SQL Server};" << "Server=" << info.url << ";" << "Database=" << info.database << ";" << "UID=" << info.user << ";" << "PWD=" << info.passwd << ";"; core::string str_conn = ss.str(); try { sta = conn->Open(str_conn.c_str(), "", "", adModeUnknown); } catch (_com_error& NNTDEBUG_EXPRESS(er)) { trace_msg((char const*)er.ErrorMessage()); return false; } catch (...) { trace_msg("failed to open database."); return false; } this->close(); d_ptr->conn = conn; # endif return true; }
DWORD CNHSQLServerDBO::OpenDB(_ConnectionPtr &pConnection) { DWORD dwReturn(0x00); // 读配置文件,获取数据库连接信息 // 获取exe(dll)文件绝对路径 wchar_t wchPath[MAX_PATH]; ZeroMemory(wchPath, sizeof(wchPath)); if (0x00 != CNHCommonAPI::GetHLDFilePath(L"Config", L"DataBase.ini", wchPath)) { return 0x01; } // 获取数据库连接信息 wchar_t wchSource[MAX_PATH]; ZeroMemory(wchSource, sizeof(wchSource)); wchar_t wchCatalog[MAX_PATH]; ZeroMemory(wchCatalog, sizeof(wchCatalog)); wchar_t wchUserID[MAX_PATH]; ZeroMemory(wchUserID, sizeof(wchUserID)); wchar_t wchPassword[MAX_PATH]; ZeroMemory(wchPassword, sizeof(wchPassword)); GetPrivateProfileString(L"Database", L"DataSource", L"", wchSource, MAX_PATH, wchPath); GetPrivateProfileString(L"Database", L"InitialCatalog", L"", wchCatalog, MAX_PATH, wchPath); GetPrivateProfileString(L"Database", L"UserID", L"", wchUserID, MAX_PATH, wchPath); GetPrivateProfileString(L"Database", L"Password", L"", wchPassword, MAX_PATH, wchPath); wchar_t wchSql[MAX_PATH]; ZeroMemory(wchSql, sizeof(wchSql)); // 加载COM组件 CoInitialize(NULL); try { _snwprintf_s(wchSql, _countof(wchSql), _TRUNCATE, L"Provider=SQLOLEDB; Data Source=%s; Initial Catalog=%s; User ID=%s; Password=%s;", wchSource, wchCatalog, wchUserID, wchPassword); pConnection.CreateInstance(L"ADODB.Connection"); //pConnection->ConnectionTimeout = 5; //pConnection->CommandTimeout = 5; pConnection->Open((_bstr_t)wchSql, L"", L"", adModeUnknown); } catch (_com_error &e) { //#ifdef _DEBUG const int nErrMsgLength(MAX_PATH); wchar_t *pwchErrMsg = new wchar_t[nErrMsgLength](); _snwprintf_s(pwchErrMsg, nErrMsgLength, _TRUNCATE, L"CNHSQLServerDBO::OpenDB发生错误(执行%s)。", wchSql); // 输出错误信息到输出窗口 OutputDebugStringW(L"\t"); OutputDebugStringW(pwchErrMsg); OutputDebugStringW(L"\n"); // 输出错误信息到日志文件 if (0 != wcscmp(m_wchLogFilePath, L"")) { // 当日志文件路径不为空时,写日志 CNHLogAPI::WriteLogEx(m_wchLogFilePath, LOG_ERR, L"NHSQLServerDBO", pwchErrMsg); } if (NULL != pwchErrMsg) { delete[] pwchErrMsg; pwchErrMsg = NULL; } OutputDBErrMsg(e); //#endif dwReturn = 0x01; } return dwReturn; }
int CCommDBOper::ADOOpenDBCon(_ConnectionPtr &pCon,const CString strDB,CString &strPassword,int iWarn) { //函数功能 打开指定数据库 //输入参数说明 pCon 要打开的数据库对象,strDB 要连接的ACCESS数据库文件全路径 // strPassword 密码 iWarn 出错警告方式 0,不警告,1,警告,2,警告且退出程序 //作者 LFX CString strCon; _TCHAR dbConnectionString[]=_T("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=%s;Jet OLEDB:Database Password=%s"); strCon.Format(dbConnectionString,strDB,strPassword); if(!PathFileExists(_T(strDB))) { WarnMessage("要打开的数据库文件名不存在!!!",iWarn); return RET_FAILED; } if (pCon == NULL) { pCon.CreateInstance(__uuidof(Connection) ); } else { ADOCloseConnectDB(pCon,0); } int iLoop = 0; while (true) { //连接ACCESS数据库 iLoop++; //如果没密码,且为第一次循环 if ( strPassword.IsEmpty() && (iLoop <= 1)) { try { pCon->Open(_bstr_t(strCon),"","",-1); } catch(_com_error &e) { CString strTemp; CInputBox inputBox; inputBox.m_bIsProtected = TRUE; strTemp.LoadString(IDS_NEEDPASSWORD); inputBox.m_strWndText.Format("%s%s",strDB,strTemp); inputBox.m_strTitle.LoadString(IDS_PLEASEINPUTDBPASSWORD); if (inputBox.DoModal() != IDOK) { WarnMessage("密码错误,打开数据库失败!!!",iWarn); return RET_FAILED; } else { strPassword = inputBox.m_strValue; } } break; } //如果有密码 try { pCon->Open(_bstr_t(strCon),"","",-1); } catch (_com_error &e) { CString strMsg; strMsg.Format("%s:%d %s", __FILE__, __LINE__, (LPSTR)e.Description()); AfxMessageBox(strMsg); CString errormessage; errormessage.Format("打开数据库 %s 失败!\r\n错误信息:%s",strDB,e.ErrorMessage()); WarnMessage(errormessage,iWarn); return RET_FAILED; } break; } //END while(true) return RET_OK; }