I have a function which is for retrieving a result set from a MySQL db here. The idea is that I want to isolate the retrieval of the data and the formating of it from each other so I've figured that I should have a function - DBI::got_ims() - that does one of two things: either it should create a vector of vector<string>s (ie. a vector of rows from the db) and then return it, or it should take a pointer (or possibly reference) to a vector< vector<string> > and assign that and return a bool as to whether it worked or not.
The first method is below (this works OK, but looks horrible):
Code:
vector< vector<string> >
DBI::got_ims( const string& to,
const string& from/*= NULL*/ )
{
/* code that uses to and from and queries the db
(it's messy and irrelevant so ommitted) */
rslt = mysql_store_result(&mysql);
if( !rslt ) this->fail(F_GOT_IMS);
if( mysql_num_rows(rslt) == 0 ){
mysql_free_result(rslt);
// return an empty set
return vector<vector<string> >();
}else{
vector<vector<string> > msgs(mysql_num_rows(rslt));
unsigned int j = 0;
unsigned int num_fields = mysql_num_fields(rslt);
while( row = mysql_fetch_row(rslt) ){
for( unsigned int k = 0; k < num_fields; k++ ){
msgs[j].push_back(row[k]);
}
++j;
}
mysql_free_result(rslt);
return msgs;
}
I can't get the other method to work, because the msgs container is only working when it has a specified size - I thought vectors were supposed to automatically resize themselves, so is there a problem in my code?
Code:
// my debugger points to here in the <vector> header as
// where a nullReferenceException occurs (only when no size for msgs is specified at allocation).
size_type size() const
{ // return length of sequence
return (_Myfirst == 0 ? 0 : _Mylast - _Myfirst);
}
Anyway it might seem like I'm not asking anything, but I thought that even though this is done in c++, the act is so common on the internet that I hoped that someone could turn around and go: 'stop being stupid, we always do that this way,' and point me to a cleaner solution.