BOOL CConnectionDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
// 初始化OLE/COM库环境
::CoInitialize(NULL);
try
{
// 创建Connection对象
m_pConnection.CreateInstance("ADODB.Connection");
// 设置连接字符串,必须是BSTR型或者_bstr_t类型
_bstr_t strConnect = "Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=HrSys;Data Source=127.0.0.1;";
m_pConnection->Open(strConnect,"","",adModeUnknown);
// 判断连接状态是否为连接
if(m_pConnection->State == adStateOpen)
MessageBox("连接数据库");
// 关闭连接
m_pConnection->Close();
// 判断连接状态是否为关闭
if(m_pConnection->State == adStateClosed)
MessageBox("断开连接");
}
// 捕捉异常
catch(_com_error e)
{
// 显示错误信息
AfxMessageBox(e.ErrorMessage());
}
return TRUE; // return TRUE unless you set the focus to a control
}
