开发者

Mysql_num_rows() Segfaults

I'm writing a program using C++ and the MySQL C API (version 5.1.31 ubuntu2). However, if the query is UPDATE then I get a Segmentation Fault error when executing the line "RowsReturned = mysql_num_rows( Result );".

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

MYSQL_RES *MYSQLDB::RunQuery( const char* Query )
{
    if( mysql_query( Connec开发者_JS百科tion, Query) )
    {
        std::cout << "Error: " << mysql_error( Connection );
        exit(1);
    }

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

    return Result;
}

Compiled using g++ 4.3.3 (g++ test.cpp -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient_r -o Test)

Thanks in advance.

//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 );
}


From the mysql documentation:

mysql_store_result() returns a null pointer if the statement didn't return a result set (for example, if it was an INSERT statement).

You are updating so you have a NULL as results.

Try something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜