我有这个代码,
class DbUpdater
{
private:
MYSQL mysql;
MYSQL *connection;
int connect()
{
mysql_init(&mysql);
this->connection = mysql_real_connect(&mysql, "localhost", "root", "password", "dbname", 0, 0, CLIENT_MULTI_STATEMENTS);
if (this->connection == NULL)
{
printf(mysql_error(&mysql));
return 0;
}
mysql_set_character_set(connection, "utf8");
return 1;
}
vector <TrackingHistory*> getTrackingHistoryByNumber(string number)
{
MYSQL_RES *result;
MYSQL_ROW row;
string query = "SELECT * FROM tracking_history WHERE number = '" + number + "' ORDER BY date DESC;";
int state = mysql_query(this->connection, query.c_str());
result = mysql_store_result(this->connection);
vector <TrackingHistory*> trackingHistory;
int numRows = mysql_num_rows(result);
while ((row = mysql_fetch_row(result)) != NULL) {
TrackingHistory *item = new TrackingHistory(atoi(row[0]), atoi(row[1]), string(row[2]), string(row[3]),
string(row[4]), string(row[5]), string(row[6]), string(row[7]), string(row[8]), string(row[9]));
trackingHistory.push_back(item);
}
mysql_free_result(result);
return trackingHistory;
}
public:
DbUpdater()
{
this->connect();
}
void UpdateDB(vector <HistoryItem*> historyItems)
{
vector <TrackingHistory*> trackingHistory = this->getTrackingHistoryByNumber( historyItems[0]->Number);
}
};
所以,我创建类的实例DbUpdater
并简单地调用方法UpdateDb()
我在函数中有一个奇怪的行为getTrackingHistoryByNumber()
int numRows = mysql_num_rows(result);
,这条线抛出一个段错误。只有当我在一个连接中执行许多查询时才会发生这种情况。如果我在每次迭代后重新连接,所有查询都可以。
例如,我有 10 个查询。当我第一次启动程序时,它会在第二次查询中引发段错误。下一次启动将在第三个查询中引发段错误。下一次开始在第 4 次查询时抛出它。
我libmysql
在 ubuntu 12.04 中使用来自 repos
这可能是什么原因?
谢谢你,对不起我的英语。