0
我在C++中實現mySQL並遇到問題。我得到一個seg故障。我不知道爲什麼。C++ Seg中的MySQL錯誤
希望有人知道發生了什麼事。
該seg故障似乎發生在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);
}
您從不真正檢查查詢(或init)是否成功,以及在調用mysql_store_result之後resSetProduct是否爲非null。另外,在'\'之後/之前還有一些額外的空格,是故意的嗎? – PhilMasterG
向前走,並刪除多餘的空間。不會這樣做(檢查查詢或resSetProduct)導致seg故障?我正在使用我爲同一個班級編寫的其他方法,並且他們工作得很好。我不是100%熟悉這一點。 – kevin
你應該檢查'mysql_real_query'是否返回零。如果沒有,'mysql_store_result'將返回NULL,'mysql_num_rows'可能會因段錯誤而失敗。 – PhilMasterG