首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL在C++断层中的应用

问MySQL在C++断层中的应用
EN

Stack Overflow用户
提问于 2017-08-06 05:03:25
回答 1查看 257关注 0票数 0

我正在用mySQL实现C++,遇到了一个问题。我出了个小毛病。我不知道为什么。

希望有人知道发生了什么。

seg故障似乎发生在MYSQL_ROW productList;线之后的某个地方,尽管如此,我还没能指出点。

代码语言:javascript
复制
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); 
} 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-06 05:37:59

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

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

一旦清除了这些错误,mysql_num_rows就不应该再进行分段错误了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45528703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档