I am writing some MYSQL embedded into C++ and I am getting some behavior that I haven't been able to pinpoint the cause of.
I have a main function and two functions that can search by author or publisher. If I search by author, I get the proper results the first time. If I search by publisher, I don't ever get any results the first time. However, no matter what I do, the second time I call one of the functions I get a segmentation fault at the line "mysql_fetch_row" in the while loops. I'm assuming I am leaving some kind of connection open that is conflicting with the second call but I have not been able to figure it out.
Sorry for the wall of code but I'm not sure where in the program the issue is coming from. I tried to describe each part and noted where the program crashes in each of the two functions.
Main function, connects to the database and calls the other two functions
#include <mysql.h>
#include <iostream>
#include <string>
using namespace std;
void searchByAuthor(MYSQL *connect);
void searchByPublisher(MYSQL *connect);
int main()
{
int choice = 0;
MYSQL *connect, mysql;
connect = mysql_init(&mysql);
//connect to the database
connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASENAME, 0,
NULL, 0);
//Get user input here to select what to search by
//Loops until user quits the program
return 0;
}
Search By Author - Gets the user input and makes the SQL call. Returns results correctly the first time.
void searchByAuthor(MYSQL *connect)
{
string name;
string sql = "select Title, Price, Type, AuthorFirst, AuthorLast from Book, Author, Wrote where Author.AuthorNum=Wrote.AuthorNum and Wrote.BookCode = Book.BookCode and AuthorLast=\'" + name + "\'";
MYSQL_RES *res_set;
MYSQL_ROW row;
cout << "Enter the last name of the author" << endl;
cin >> name;
mysql_query(connect, (sql).c_str());
res_set = mysql_store_result(connect);
//Crashes here on second call
while ((row = mysql_fetch_row(res_set)) != NULL)
{
cout << endl << row[0] << " "
<< row[1] << " " << row[2] << " "
<< row[3] << " " << row[4] << endl;
}
mysql_free_result(res_set);
mysql_close(connect);
}
Search By Publisher - Gets user input and makes the SQL call - Does not ever return any results.
void searchByPublisher(MYSQL *connect)
{
string publisher;
string sql = "select Book.Title from Book, Publisher where Publisher.PublisherName =\'" + publisher + "\' and Publisher.PublisherCode = Book.PublisherCode";
MYSQL_RES *res_set;
MYSQL_ROW row = NULL;
cout << "Enter the name of the publisher" << endl;
cin >> publisher;
mysql_query(connect, sql.c_str());
res_set = mysql_store_result(connect);
//Crashes here on second call
while ((row = mysql_fetch_row(res_set)) != NULL)
{
cout << endl << row[0] << endl;
}
mysql_free_result(res_set);
mysql_close(connect);
}
mysql_fetch_row? The segfault should happen when trying to printrow[0]if it's null.mysql_fetch_rowfunction call, or when you dostd::cout << ....