1.前言
前段时间有一小朋友拿着作业本问我一个四字成语什么花什么妍,想了半天没反应过来,后来百度了下才告诉人家,决定写一个软件实现四字成语的查询,目前收录了两部资源 <<中国成语大辞典>>和<<成语大全>>,查询在毫秒级别
2.思想
2.1加载外部资源如中国成语大辞典和成语大全到sqlite数据库中
@H_
301_9@2.2通过模糊
查询获取数据库中的相关信息并进行展示
int nsum = 0;
std::vector<std::string> vecname;
DWORD dwBeg = GetTickCount();
std::fstream srcfile;
srcfile.open("成语大全.txt",std::ios_base::in);
if (srcfile.is_open())
{
std::string strline("");
while (srcfile>>strline)
{
int nfirst = strline.find("拼音");
if (nfirst != -1)
{
std::string strvalue = strline.substr(0,nfirst);
if (!strvalue.empty())
{
strvalue = trim(strvalue);
std::string strutf8 = MbsToUtf8(strvalue);
vecname.push_back(strutf8);
nsum++;
}
}
}
}
srcfile.close();
if (!vecname.empty())
m_sqlite.insertdb(vecname);
TCHAR ptBuf[MAX_PATH] = {0};
swprintf_s(ptBuf,MAX_PATH,TEXT("共收录%d条成语,耗时:%d秒."),nsum,(GetTickCount() - dwBeg) / 1000);
AfxMessageBox(ptBuf);
std::string strvalue("");
char szbuf[64] = {0};
GetDlgItemTextA(GetSafeHwnd(),IDC_EDIT1,szbuf,64);
if (strlen(szbuf) > 0)
strvalue += szbuf;
else
strvalue += "_";
GetDlgItemTextA(GetSafeHwnd(),IDC_EDIT2,IDC_EDIT3,IDC_EDIT4,64);
if (strlen(szbuf) > 0)
strvalue += szbuf;
else
strvalue += "_";
CListBox *plistBox = (CListBox *)GetDlgItem(IDC_LIST1);
plistBox->ResetContent();
std::string strutf8 = MbsToUtf8(strvalue);
std::vector<std::string> vecname;
m_sqlite.selectdb(strutf8,vecname);
if (vecname.empty())
AfxMessageBox(_T("抱歉,没有找到相关程序,请点击进行收录"));
else
{
USES_CONVERSION;
for (int nindex = 0; nindex < vecname.size(); ++nindex)
{
strvalue = Utf8ToMbs(vecname[nindex]);
plistBox->InsertString(nindex,A2T(strvalue.c_str()));
}
}
3.3操作数据库的接口
bool CsqliteIdiom::insertdb(const std::string &strname)
{
bool bret = false;
if (m_pDB != nullptr)
{
std::string strsql = "";
strsql += "insert into tb_idiom(name)";
strsql += "values('";
strsql += strname;
strsql += "');";
char* cErrMsg;
int nRes = sqlite3_exec(m_pDB,strsql.c_str(),0,&cErrMsg);
bret = nRes == sqlITE_OK;
}
return bret;
}
bool CsqliteIdiom::insertdb(const std::vector<std::string> &vecname)
{
bool bret = false;
if (m_pDB != nullptr)
{
sqlite3_exec(m_pDB,"BEGIN;",0);
for (std::vector<std::string>::const_iterator it = vecname.begin(); it != vecname.end(); ++it)
{
std::string strsql = "";
strsql += "insert into tb_idiom(name)";
strsql += "values('";
strsql += *it;
strsql += "');";
sqlite3_exec(m_pDB,0);
}
sqlite3_exec(m_pDB,"COMMIT;",0);
bret = true;
}
return bret;
}
bool CsqliteIdiom::selectdb(const std::string &strname,std::vector<std::string> &allname)
{
bool bret = false;
if (m_pDB != nullptr)
{
char **dbResult;
char *errmsg;
int nRow,nColumn;
int index=0;
std::string strsql = "";
strsql += "select name from tb_idiom where name like '%";
strsql += strname;
strsql += "%'";
int rc = sqlite3_get_table( m_pDB,&dbResult,&nRow,&nColumn,&errmsg);
if (rc == sqlITE_OK)
{
index = nColumn;
for(int i = 0; i < nRow ; i++ )
{
for(int j = 0 ; j < nColumn; j++ )
allname.push_back(dbResult[index++]);
}
}
bret = true;
}
return bret;
}
4.备注
4.1 vs2010+win7(64位旗舰版)+sqlite3 编译测试通过