Pim Pim - 1 month ago 6
C++ Question

Looping through the resultset

I'm using the MySQL C++ connector and I'm trying to iterate through the resultset in the following way: The application should iterate through every column, not depending on the data type. The code should catch the data type and then proceed. The problem is that the table I'm testing with has 16 columns, but my code only runs through the first one?

try
{
driver = get_driver_instance();
con = driver->connect(connectionString, str_username, str_password);
con->setSchema(str_schema);
stmt = con->createStatement();
res = stmt->executeQuery(selectquery);
res_meta = res->getMetaData();

string datatype;
int columncount = res_meta->getColumnCount();

for (int i = 0; i < columncount; i++)
{
while (res->next())
datatype = res_meta->getColumnTypeName(i + 1);
{
if(datatype == "INT")
{
switch (res_meta->getColumnDisplaySize(i + 1))
{
case 64:
break;
case 32:
break;
default:
break;
}
}
}
}
catch(sql::SQLException &e){}

Answer

When accessing an RDBMS, the ResultSet you get is typically row-oriented. That is to say, whenever you call ResultSet::next(), the cursor moves on to the next row. That is why your loop

for (int i = 0; i < columncount; i++)
{                 
    while (res->next())
    {
        ...
    }
}

is only showing the first attribute.

Normally you switch inner and outer loops such as

while (res->next())
{
    for (int i = 0; i < columncount; i++)
    {
        ...
    }
}

But if you really need to access one column at a time, you'll have to check if the ResultSet allows you to reset the cursor to the first row. If not, you either have to cache the data, or issue the same SQL query over and over again.

Comments