我正在编写一些嵌入到 C++ 中的 MYSQL,但出现了一些我无法查明原因的行为。
我有一个主要功能和两个可以按作者或出版商搜索的功能。如果我按作者搜索,我会在第一时间得到正确的结果。如果我按出版商搜索,我第一次不会得到任何结果。但是,无论我做什么,第二次调用其中一个函数时,我在 while 循环中的“mysql_fetch_row”行遇到了段错误。我假设我正在打开某种与第二次调用冲突的连接,但我一直无法弄清楚。
对于代码墙,我深表歉意,但我不确定问题出在程序的哪个位置。我试图描述每个部分,并指出程序在两个函数中的每一个中崩溃的位置。
主函数,连接数据库,调用其他两个函数
#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;
}
按作者搜索 - 获取用户输入并进行 SQL 调用。第一次正确返回结果。
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);
}
按发布者搜索 - 获取用户输入并进行 SQL 调用 - 永远不会返回任何结果。
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_close(connect)
关闭连接,但不确定是否在再次查询之前重新打开连接?检查here当您关闭它时, handle 也会关闭。
同时检查你的 mysql 数据库是否有空值。
关于c++ - 第二次调用 mysql_fetch_row 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980398/