ホームページ >データベース >mysql チュートリアル >详解MFC使用ADO连接SQLServer数据库
VC用ADO访问 数据库 全攻略,介绍了VC用ADO来访问 数据库 的各个对象及各方法,很经典,也很实用,很得一看。 正文 一、ADO概述 ADO是Microsoft为最新和最强大的数据访问范例 OLE DB 而设计的,是一个便于 使用 的应用程序层接口。ADO 使您能够编写应用程序以
VC用ADO访问数据库全攻略,介绍了VC用ADO来访问数据库的各个对象及各方法,很经典,也很实用,很值得一看。_ConnectionPtr主要是一个连接接口,取得与数据库的连接。它的连接字符串可以是自己直接写,也可以指向一个ODBC DSN。
_ConnectionPtr pConn; if (FAILED(pConn.CreateInstance("ADODB.Connection"))) { AfxMessageBox("Create Instance failed!"); return; } CString strSRC; strSRC="Driver=SQL Server;Server="; strSRC+="suppersoft"; strSRC+=";Database="; strSRC+="mydb"; strSRC+=";UID=SA;PWD="; CString strSQL = "Insert into student(no,name,sex,address) values(3,"aaa","male","beijing")"; _variant_t varSRC(strSRC); _variant_t varSQL(strSQL); _bstr_t bstrSRC(strSRC); if (FAILED(pConn->Open(bstrSRC,"","",-1))) { AfxMessageBox("Can not open Database!"); pConn.Release(); return; } COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR); pConn->Execute(_bstr_t(strSQL),&vtOptional,-1); pConn.Release(); AfxMessageBox("ok!");
5、使用_RecordsetPtr接口(以连接SQL Server为例)
_RecordsetPtr pPtr; if (FAILED(pPtr.CreateInstance("ADODB.Recordset"))) { AfxMessageBox("Create Instance failed!"); return FALSE; } CString strSRC; strSRC="Driver=SQL Server;Server="; strSRC+="210.46.141.145"; strSRC+=";Database="; strSRC+="mydb"; strSRC+=";UID=sa;PWD="; strSRC+="sa"; CString strSQL = "select id,name,gender,address from personal"; _variant_t varSRC(strSRC); _variant_t varSQL(strSQL); if(FAILED(pPtr->Open(varSQL,varSRC,adOpenStatic,adLockOptimistic,adCmdText))) { AfxMessageBox("Open table failed!"); pPtr.Release(); return FALSE; } while(!pPtr->GetadoEOF()) { _variant_t varNo; _variant_t varName; _variant_t varSex; _variant_t varAddress; varNo = pPtr->GetCollect ("id"); varName = pPtr->GetCollect ("name"); varSex = pPtr->GetCollect ("gender"); varAddress = pPtr->GetCollect ("address"); CString strNo =(char *)_bstr_t(varNo); CString strName =(char *)_bstr_t(varName); CString strSex =(char *)_bstr_t(varSex); CString strAddress =(char *)_bstr_t(varAddress); strNo.TrimRight(); strName.TrimRight(); strSex.TrimRight(); strAddress.TrimRight(); int nCount = m_list.GetItemCount(); int nItem = m_list.InsertItem (nCount,_T("")); m_list.SetItemText (nItem,0,strNo); m_list.SetItemText (nItem,1,strName); m_list.SetItemText (nItem,2,strSex); m_list.SetItemText (nItem,3,strAddress); pPtr->MoveNext(); } pPtr->Close(); pPtr.Release();
代码11:使用_CommandPtr接口获取数据
_CommandPtr pCommand; _RecordsetPtr pRs; pCommand.CreateInstance(__uuidof(Command)); pCommand->ActiveConnection=pConn; pCommand->CommandText="select * from student"; pCommand->CommandType=adCmdText; pCommand->Parameters->Refresh(); pRs=pCommand->Execute(NULL,NULL,adCmdUnknown); _variant_t varValue = pRs->GetCollect("name"); CString strValue=(char*)_bstr_t(varValue);