我有这段代码,
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个查询。 当我第一次启动程序时,它会在第二次查询时抛出段错误。 下一步将在第三次查询时抛出segfault。 接下来的开始会在第4次查询时抛出它。
我在ubuntu 12.04中使用repos中的libmysql
这可能是什么原因?
谢谢你,对不起我的英语。