使用pqxx游标

时间:2019-06-06 03:50:31

标签: postgresql libpqxx

我正在尝试学习如何在pqxx中使用游标。

我在参考文献中发现了pqxx::cursor_base,并且从pqxx::cursor_base派生了几个子类。

搜索了几个小时的主题之后,我找不到任何示例代码或任何解释如何使用pqxx游标的东西。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

令人惊讶的是,几乎找不到光标示例。这是我的用途:

      const std::conStr("user=" + opt::dbUser + " password=" + opt::dbPasswd + " host=" + opt::dbHost + " dbname=" + opt::dbName);                                            

      pqxx::connection conn(connStr);
      pqxx::work txn(conn);
      std::string selectString = "SELECT id, name FROM table_name WHERE condition";

      pqxx::stateless_cursor<pqxx::cursor_base::read_only, pqxx::cursor_base::owned> 
      cursor(txn, selectString, "myCursor", false);

      //cursor variables
      size_t idx = 0;       //starting location
      size_t step = 10000;  //number of rows for each chunk
      pqxx::result result;
      do{
        //get next cursor chunk and update the index
        result = cursor.retrieve( idx, idx + step );
        idx += step;

        size_t records = result.size();
        cout << idx << ": records pulled = " << records << endl;

        for( pqxx::result::const_iterator row : result ){
          //iterate over cursor rows
        }
      }
      while( result.size() == step ); //if the result.size() != step, we're on our last loop
      cout << "Done!" << endl;