您的位置:首页 > 数据库

MFC ado远程连接MSSQL

2013-10-14 13:18 459 查看
在stdafx.h中引入:
#import"C:\ProgramFiles\CommonFiles\System\ado\msado15.dll"no_namespacerename("EOF","adoEOF")
添加变量:
_ConnectionPtrm_pConnection;
_RecordsetPtrm_pRecordset;
连接数据库:
	CoInitialize(NULL);m_pConnection.CreateInstance(_T("ADODB.Connection"));///创建Connection对象m_pConnection->ConnectionTimeout=8;try{HRESULThr;hr=m_pConnection->Open(_T("Provider=SQLOLEDB.1;DataSource=127.0.0.1,1433;InitialCatalog=databasename;"),_T("sa"),_T("sapwd"),adModeUnknown);if(FAILED(hr)){AfxMessageBox(_T("不能连接数据库!"));returnFALSE;}else{AfxMessageBox(_T("连接数据库成功!"));}}catch(_com_errore){AfxMessageBox(_T("不能打开数据库!"));returnfalse;}
读取数据表:
		CStringstrTableName=_T("");m_pRecordset=m_pConnection->OpenSchema(adSchemaTables);if(!m_pRecordset->BOF){m_pRecordset->MoveFirst();}while(!m_pRecordset->adoEOF){strTableName=(LPCSTR)_bstr_t(m_pRecordset->GetFields()->GetItem(_T("TABLE_NAME"))->Value);//MessageBox(strTableName);m_pRecordset->MoveNext();m_ctrlListTables.InsertString(m_ctrlListTables.GetCount(),strTableName);}
读取数据:
			CStringSQLStr;SQLStr.Format(_T("selecttop1*fromtest"));m_pRecordset.CreateInstance(__uuidof(Recordset));m_pRecordset->Open(_bstr_t(SQLStr),m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);while(!m_pRecordset->adoEOF){CStringstr;str=(LPCSTR)_bstr_t(m_pRecordset->GetFields()->GetItem(_T("id"))->Value);//MessageBox(strTableName);m_pRecordset->MoveNext();m_ctrlListTables.InsertString(m_ctrlListTables.GetCount(),str);}
插入数据:
			CStringstrCommand=_T("");strCommand.Format(_T("INSERTINTOA_cpavalues('%s','%d','%s','%s','%s','%d','%s','%d','%s','%s','%s','%s','%s')"),LMuname,LMID,lailuURL,addtime,cpaUser,ok,regip,sex8,browser,mima,os,fbl,wwwurl);try{m_pConnection->Execute((_bstr_t)strCommand,NULL,adCmdText);}catch(_com_error&e){//MessageBox(e.ErrorMessage());returnfalse;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: