Mysql_num_rows()Segfaults

时间:2009-11-08 10:49:42

标签: c++ mysql segmentation-fault

我正在使用C ++和MySQL C API(版本5.1.31 ubuntu2)编写程序。但是,如果查询是 UPDATE ,那么在执行“RowsReturned = mysql_num_rows(Result);”行时会出现 Segmentation Fault 错误。

//this code snippet contains only the relevant code
MYSQL_RES *Result;
long RowsReturned;

MYSQL_RES *MYSQLDB::RunQuery( const char* Query )
{
    if( mysql_query( Connection, Query) )
    {
        std::cout << "Error: " << mysql_error( Connection );
        exit(1);
    }

    Result = mysql_store_result( Connection );
    RowsReturned = mysql_num_rows( Result );

    return Result;
}

使用g ++ 4.3.3编译(g ++ test.cpp -I / usr / include / mysql -L / usr / lib / mysql -lmysqlclient_r -o Test)

提前致谢。

//this snippet contains the entire class code
class MYSQLDB
{

public:
    void Connect( const char* DB );
    MYSQL_RES *RunQuery( const char* Query );  
    long NumRows();
    void Close();
    MYSQL_ROW GetRow();
private:
    MYSQL *Connection;
    MYSQL_RES *Result;
    MYSQL_ROW Row;

    long RowsReturned;
};

void MYSQLDB::Connect( const char* DB )
{
    Connection = mysql_init( NULL );

    if( Connection == NULL )
    {
        std::cout << "Error: " << mysql_error( Connection );
        exit( 1 );
    }

    if ( mysql_real_connect( Connection, "localhost", "root", "password", DB, 0, NULL, 0 ) == NULL)
    {
        std::cout << "Error: " << mysql_error( Connection );
        exit(1);
    }
}

MYSQL_RES *MYSQLDB::RunQuery( const char* Query )
{
    if( mysql_query( Connection, Query) )
    {
        std::cout << "Error: " << mysql_error( Connection );
        exit(1);
    }

    Result = mysql_store_result( Connection );
    RowsReturned = (long)mysql_num_rows( Result ); //ERROR!!!!!!!

    return Result;
}

long MYSQLDB::NumRows()
{
    return RowsReturned;
}

void MYSQLDB::Close()
{
    mysql_free_result( Result );
    mysql_close( Connection );
}

MYSQL_ROW MYSQLDB::GetRow()
{
    return mysql_fetch_row( Result );
}

1 个答案:

答案 0 :(得分:3)

来自mysql文档:

如果语句没有返回结果集,则mysp_store_result()返回空指针(例如,如果它是INSERT语句)。

您正在更新,因此您的结果为NULL。

尝试这样的事情:

Result = mysql_store_result( Connection );
if (Result) {
    RowsReturned = mysql_num_rows( Result );
} else {
    RowsReturned = 0;
}