1、导入库文件,并设置全局连接字符串
#import "C:\Program Files\Common Files\System\ado\msado60_Backcompat_i386.tlb" no_namespace rename("EOF","EndOfFile") _ConnectionPtr pConn=NULL; //数据库连接
2、在工程目录下新建SQL_connect.ini文件,并输入
Provider=MSDAORA.1;Password=test;User ID=test;Data Source=127.0.0.1:1521/orcl;Persist Security Info=True127.0.0.1是指本机,如果连接到其他IP,直接修改该地址即可
连接数据库
if (!AfxOleInit()) //初始化OLE/COM库 { AfxMessageBox(_T("OLE init Error")); return FALSE; } //创建数据库连接实例 CStdioFile file; file.Open(_T("SQL_Connect.ini"), CFile::modeRead); CString str=_T(""); file.ReadString(str); file.Close(); const _bstr_t strSRC = (_bstr_t)str; //const _bstr_t strSRC= "Provider=MSDAORA.1;Password=test;User ID=test;Data Source=localhost:1521/orcl;Persist Security Info=True"; if (FAILED(pConn.CreateInstance("ADODB.Connection"))) { AfxMessageBox(_T("Create Instance failed!")); exit(0); } try { pConn->Open(strSRC,"","",adModeUnknown); } catch(_com_error e) { AfxMessageBox(e.Description()); exit(0); }
3、查询数据库
<pre name="code" class="cpp"> CString str="R4-012345A010"; CString coilnum; _variant_t RecordsAffected; _RecordsetPtr pRecordset; //钢卷1 str.Format(_T("select coilnum from test.test2 where coilnum like '%s'"), str); pRecordset = pConn->Execute((_bstr_t)str,&RecordsAffected,adCmdText); //查询历史数据中当前卷信息 if (!(pRecordset->BOF||pRecordset->EndOfFile) ) //存在历史数据 { _variant_t var; var = pRecordset->GetFields()->GetItem((long)0)->GetValue(); if(var.vt != VT_NULL) //为NULL {m_coilnum = var;} else {m_coilnum = "";} }