65.9K
CodeProject 正在变化。 阅读更多。
Home

简单的 count() 查询类

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.04/5 (8投票s)

2004 年 8 月 17 日

viewsIcon

37258

downloadIcon

423

一个用于轻松执行 count() 查询的类。

引言

这个简单的类使用基本的 CRecordset 来实现 count() 查询。 通过发出 SQL 语句来完成它并不难,捕获返回值也并非一定很困难。 这个类只是让它更容易。

背景

我将此代码作为更大的数据库应用程序的一部分编写的。 从那以后,我多次重用了这段代码,所以我想它对其他人也可能有用。

使用代码

要使用这段代码,只需将代码和头文件添加到您的项目中。 您需要在 countset.cpp 中编辑一行

CString CCountSet::GetDefaultConnect()
{
    return _T("ODBC;DSN=WinTAS");  // put your own DSN in here
}

然后只需在您想要使用它的头文件中 #include countset.h,并按照示例进行设置

CCountSet countSet;
countSet.sSelect="some SQL statement returning a numeric value, 
    such as MAX(age)";  // delete this line to use the next one
countSet.sDistinct="field name for select(distinct <fieldname>) 
    statement";  // delete this line for select(*);
countSet.sCheckTable="table name you're counting in"; 
// this is just appended to the SQL,
// so could include JOIN statements

countSet.sCheckField="WHERE condition for SQL statement";
// delete for no WHERE clause

countSet.Open();
// never Requery() it: Close() and Open() if you want to re-use it.

// return value is in countSet.m_TOTAL;

所以,这就是它 - 声明一个 CCountSet 的实例,设置一些变量,然后就可以开始了。 例如,要生成 SQL 语句 count(max(age)) from client,您可以这样编写

CCountSet countSet;
CString sText;

countSet.sSelect="MAX(age)";
countSet.sCheckTable="client";
countSet.Open();
sText.Format("The oldest client is %d",countSet.m_TOTAL);
AfxMessageBox(sText);
© . All rights reserved.