日期:2014-05-16  浏览次数:20955 次

求助。。。select count 的赋值问题
代码是这样的

int32 CDataBase::CountRecord(TABLE_PARAM *pParam)
{
char str[512];
MYSQL_RES *p;
int32 cnt;

sprintf(str,"select count(*) as cnt from %s",pParam->tab_name);

mysql_query(&m_Mysql,"set names gbk");
p=GetResult(str);
 
  ?????

return cnt;
}

求助!我应该怎么样才能将返回的记录总数值赋给变量cnt呢?

------解决方案--------------------
sigh,我还是写一个简单的demo,关于错误处理部分,你自己去完善吧。mysql的C-API还是蛮清晰的,比Oracle和Sybase ASE的简单多了。

C/C++ code
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>


static const char host[32] = "localhost";
static const char user[32] = "test";
static const char passwd[32] = "********";
static const char db[32] = "test";


//
// Just for demo only.
// 
int main()
{

    MYSQL*              mysql_ = NULL;
    MYSQL_RES*          result_ = NULL;
    MYSQL_ROW           row_;

    mysql_ = mysql_init(mysql_);

    if (mysql_real_connect(mysql_, host, user, passwd, db, 3306, NULL, 0) == NULL)
    {
        const char * error = mysql_error(mysql_);
        std::cout<<"*** Connection Error " << error << std::endl;

        return -1;
    }
    mysql_autocommit(mysql_, false);

    std::string encodeStr = "set names 'gbk'";
    mysql_real_query(mysql_, encodeStr.c_str(), encodeStr.size());
    

    const char* tmpTableName = "t";  // assume you are querying the table 't'
    char str[512];
    int cnt = 0;
    sprintf(str,"select count(*) as cnt from %s", tmpTableName);

    mysql_real_query(mysql_, str, strlen(str));
    result_ = mysql_store_result(mysql_);
    while (row_ = mysql_fetch_row(result_))
    {
        // get the field value
        if (row_[0])
        {
            std::cout<<"count = "<<row_[0]<<std::endl;
            // convert it into int
            cnt = atoi(row_[0]);
            std::cout<<"cnt value = "<<row_[0]<<std::endl;
        }
    }

    mysql_free_result(result_);
    mysql_close(mysql_);
    return 0;
}