1. 程式人生 > >VS2010中MFC連線Sql Server 2012方法

VS2010中MFC連線Sql Server 2012方法

  1. //初始化資料庫連線
    ::CoInitialize(NULL);

  2. 連線資料庫
    BOOL CLogin::ConnectDB(void)
    {
    	HRESULT hr = NULL;
    	try 
    	{
    		hr = m_pConnection.CreateInstance("ADODB.Connection");///建立 Connection 物件 
     
    		if(SUCCEEDED(hr))   
    		{
    			//登入資料庫並連線資料庫DBCourse
    			//這裡的server不能寫成127.0.0.1否則會出現未指定的錯誤,應該寫成Sql server登入介面的伺服器名稱
    			m_pConnection->ConnectionString = "driver={SQL Server};server=LOGO-PC\\LOGO;uid=DBCourse;pwd=DBCourse;";
    			m_pConnection->Open("","","",adConnectUnspecified);
    			m_pConnection->DefaultDatabase = "DBCourse";
    		}
    		else
    		{
    			AfxMessageBox(TEXT("建立 Connection 物件失敗"));///顯示錯誤資訊
    			return FALSE;
    		}
    	}   
    	catch(_com_error e)///捕捉異常   
    	{ 
    		CString errormessage;
    		errormessage.Format( TEXT("連線資料庫失敗 !\r\n 錯誤資訊 :%s(%ld)"),e.ErrorMessage(),e.Error() ); 
    		AfxMessageBox(errormessage);///顯示錯誤資訊  
    		return FALSE;
    	}
    	return TRUE;
    }

  3. 操作資料庫
    void CLogin::OnBnClickedButton1()
    {
    	if( m_user.GetWindowTextLength()<=0 || m_password.GetWindowTextLength()<=0 )
    	{
    		MessageBox(TEXT("請輸入使用者名稱或密碼!"), TEXT("錯誤:使用者名稱或密碼為空"), MB_OK | MB_ICONWARNING );
    		return;
    	}
    	if( FALSE==this->ConnectDB() ) return;
    
    	TCHAR szUserName[20];
    	TCHAR szPassword[50];
    	TCHAR szSql[MAX_PATH];
    	
    	//獲取使用者輸入的使用者名稱和密碼
    	m_user.GetWindowText( szUserName, 20 );
    	m_password.GetWindowText( szPassword, 50 );
    
    	//建立_RecordsetPtr用來執行資料庫操作
    	_RecordsetPtr pRecordset;
    	pRecordset.CreateInstance("ADODB.Recordset");
    
    	_tcscpy_s( szSql, TEXT("select * from usr where uname='") );
    	_tcscat_s( szSql, szUserName );
    	_tcscat_s( szSql, TEXT("' and passwd='") );
    	_tcscat_s( szSql, szPassword );
    	_tcscat_s( szSql, TEXT("';") );
    	pRecordset->Open(_variant_t(szSql),  _variant_t  ((IDispatch*) m_pConnection,true), adOpenStatic, adLockOptimistic, adCmdText);
    	
    	int nResult = DLG_RESULT_OK;
    	if( pRecordset->RecordCount>0 )
    	{
    		//MessageBox(TEXT("登入成功!"), szUserName, MB_OK | MB_ICONINFORMATION );
    	}
    	else
    	{
    		MessageBox(TEXT("使用者名稱或密碼錯誤!"), TEXT("登入失敗!"), MB_OK | MB_ICONINFORMATION );
    		nResult = DLG_RESULT_ERROR;
    	}
    	pRecordset->Close();
    	if( DLG_RESULT_OK==nResult ) Exit( DLG_RESULT_OK );
    }

  4. 哦忘了一件事了,還需要在stafx.h檔案中引入dll檔案的,如此
    //新增dll庫
    #import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF") 
    //新增dll庫
    
    //新增巨集定義
    #define DLG_RESULT_OK     1
    #define DLG_RESULT_ERROR  2
    #define DLG_RESULT_CANCEL 3
    //新增巨集定義
    
    即可!
  5. 此致,敬禮,完畢!