c++ - C++ 中的 MySQL 段错误

标签 c++ mysql

我正在用 C++ 实现 mySQL,但遇到了问题。我遇到了段错误。我不知道为什么。

希望有人知道发生了什么事。
段错误似乎发生在MYSQL_ROW productList;之后的某个地方。线,但我无法确定在哪里。

void Receiving::getProduct(const string productToReturn) { 
MYSQL *connect, mysql;                  //Pointers to MySQL
connect = mysql_init(&mysql);           // Initialize the connections
int totalRows = 0;

connect = mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0);  //Connect to database 

if(connect) {                           //If connection successful
    string sqlQuery;                    //will hold query

    MYSQL_RES *resSetProduct;           //define product result set
    MYSQL_ROW productList;              //define row for product

    sqlQuery = "SELECT * FROM Inventory WHERE item_id = \' "; //Create query with desired product id
    sqlQuery += productToReturn;
    sqlQuery += " \'";

    mysql_query(connect, sqlQuery.c_str());                                    // Send query to the database
    resSetProduct = mysql_store_result(connect);                               // Receive the result and store it in resSetProduct
    totalRows = mysql_num_rows(resSetProduct);                                 // count of stored rows

    if(totalRows == 0){                                                        //nothing found
        cout << "Sorry! No inventory found for that product!" << endl;
    }
    else {
        cout << "Product Id     In Stock" << endl;

        while( (productList = mysql_fetch_row(resSetProduct)) != NULL ) {      //printout the products
            cout << productList[0] << "    " << productList[1] << endl;
        }
    }
    mysql_free_result(resSetProduct);
}
else                                                                           //Failed to connect
    cerr << "Failed To Connect!";

mysql_close(connect); 
} 

最佳答案

您应该检查mysql_query是否返回零。如果没有,mysql_store_result 将返回 NULL,mysql_num_rows 可能会因段错误而失败。

如果mysql_query返回非零,您可以根据mysql文档检查错误代码,例如:这里:MySQL mysql_query

一旦这些错误被清除,mysql_num_rows就不会再出现段错误了。

关于c++ - C++ 中的 MySQL 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45528703/

相关文章:

c++ - 这个循环将如何结束

c++ - 在加载时分配/保留具有已知地址的 avr sram 以适应 progspace

c++ - 快速的线程间通信机制

mysql - #1066 - 不是唯一的表/别名 :

mysql尝试使用多个条件进行选择

php - 使用可点击文本为变量赋值

c++ - 如何在for循环中使用指针来统计字符?

c++ - 如何将我的类模板传递给函数? (C++)

php - 数据没有插入到表中?

mysql - 如果条件满足则跳出 IF 语句