当前位置:首页 > C++编程常用模块
1(一):连接SQL数据库
一、连接数据库(SQL): (一)直接写在程序中 1、导入动态连接库 在StdAfx.h中:
#import \rename(\2、定义Provider宏 在StdAfx.h中:
#define Provider \Persist Security Info=False;Initial Catalog=HRMS\ 3、初始化
a) .h文件中 private:
HDC m_hDC;
DWORD m_CurrentRecord; _RecordsetPtr m_pRecordset; _ConnectionPtr m_pConnection; b) .cpp文件中
CADOOperation::CADOOperation() {
try{
m_pConnection.CreateInstance(_uuidof(Connection));
m_pConnection->Open(_bstr_t(Provider), \ }
catch(_com_error e) {
AfxMessageBox(e.Description(), MB_OK); exit(0); }
m_pRecordset.CreateInstance(_uuidof(Recordset)); m_CurrentRecord = -1; } 4、执行 5、关闭
CADOOperation::~CADOOperation() {
m_pConnection->Close(); }
(二)通过login.ini文件连接 void CBbbApp::IniAdo() {
try
{ CString temp;
char filepath[MAX_PATH];
GetModuleFileName(NULL,filepath,MAX_PATH);
temp = theApp.ExtractFilePath(filepath);//获取可执行文件的路径,也就是程序运行的.exe文件所在路径
//运行后,temp的值为程序文件.exe 所在路径
CString strAdoConn; char temp1[100];
/*********************************************
在同目录下创建login.ini文件,并在其中设置数据库连接字符串,如: [DatabaseConfig]
Server=. // . 表示本机 Database=BookManage User=sa PWD=sa
*********************************************/
GetPrivateProfileString(\
strserver = (TCHAR *)temp1;
GetPrivateProfileString(\
strdbName = temp1;
GetPrivateProfileString(\
strUser = temp1;
GetPrivateProfileString(\
strPassword = temp1;
strAdoConn.Format(\Server};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s\
strserver, strUser, strPassword, strdbName);
m_pCon.CreateInstance(_uuidof(Connection));
m_pCon->ConnectionString = (_bstr_t)strAdoConn; m_pCon->Open(\
m_pCom.CreateInstance(\ m_pRs.CreateInstance(_uuidof(Recordset));
m_pRs1.CreateInstance(_uuidof(Recordset)); // ADOFLAG = TRUE; }
catch(_com_error) {
//ADOFLAG = FALSE; Flag = FALSE;
MessageBox(0,\请检查系统配置信息\数据库连接失败\
return; } catch(...) {
AfxMessageBox(\ return ; } }
共分享92篇相关文档