本文介绍了遍历结果集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MySQL C++ 连接器,并尝试通过以下方式遍历结果集:应用程序应该遍历每一列,而不是依赖于数据类型.代码应该捕获数据类型,然后继续.问题是我正在测试的表有 16 列,但我的代码只运行第一个?

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){}

推荐答案

在访问 RDBMS 时,您获得的 ResultSet 通常是面向行的.也就是说,每当您调用 ResultSet::next() 时,光标都会移动到下一行.这就是为什么你的循环

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())
    {
        ...
    }
}

只显示第一个属性.

通常你会切换内循环和外循环,例如

Normally you switch inner and outer loops such as

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

但如果您确实需要一次访问一列,则必须检查 ResultSet 是否允许您将光标重置到第一行.如果没有,您要么必须缓存数据,要么一遍又一遍地发出相同的 SQL 查询.

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.

这篇关于遍历结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:51