写了一个通用的查询Sql的函数 ----VC新手

xiaoxiao2021-03-01  31

查询数据库的操作是VC最基本的,通过研究,自己写了一个通用的VC查询的函数,不足之处,请各位指正。如下:

int ExcelSqlOne(char *one,CString fieldName,char szsql[])//One返回查询表里面的字段的数据,fieldName是表的字段,szsql是查询语句,如select * from Tabel { long nRecordId = 0;

//连接数据库 if (m_bDBOpened == FALSE) { m_bDBOpened=OpenDB(); } if (m_bDBOpened == FALSE) { g_tLog.print("OpenDB fail.\n"); return -1; }

long nRet=0;

char sql[1024]; sprintf(sql,"%s",szsql); g_tLog.print("SQL:%s\n",sql); try { _CommandPtr pCmd; pCmd.CreateInstance(__uuidof(Command)); pCmd->ActiveConnection = m_pConn; pCmd->CommandText =_bstr_t(sql);

pCmd->Parameters->Refresh(); pCmd->CommandType = adCmdText;

_RecordsetPtr pRs=pCmd->Execute(NULL,NULL,adCmdText);

if (pRs->GetState() == adStateClosed ||pRs->adoEOF) { return -1; }

if (pRs->GetState() != adStateClosed && !pRs->adoEOF)//while {

CString strTemp=""; _variant_t var;

//Id var.Clear(); strTemp.Empty(); _variant_t varFiled =(LPCTSTR)fieldName; var=(LPTSTR)_bstr_t(pRs->GetCollect(varFiled)); if (var.vt!=VT_NULL&&var.vt!=VT_EMPTY) { strTemp=(LPTSTR)_bstr_t(var); strTemp.TrimLeft(); strTemp.TrimRight(); } lstrcpy(one, strTemp); nRecordId = atol(strTemp); g_tLog.print("nRecordId(%d)\n",nRecordId); return nRecordId; } } catch (_com_error& e) { CloseDB(); g_tLog.print("com_error:%s,%s\n",(LPTSTR)e.Description(),sql); return -1; } catch (...) { CloseDB(); g_tLog.print("error:%s,%s\n","出错,关闭数据库",sql); return -1; }

return nRecordId;//nRet; }

这个函数打开数据库的OpenDB()和CloseDB(),在这里不再列出了,初函数的调用如下: char ss[1024],filed[200]; sprintf(ss,"%s","select * from voice"); CString dd; dd.Format("Id"); srDbconn.ExcelSqlOne(filed,dd,ss); g_tLog.print("%s\n",filed);

相关资源:JAVA上百实例源码以及开源项目源代码
转载请注明原文地址: https://www.6miu.com/read-4049937.html

最新回复(0)