【问题标题】:Getting started with MongoDB C++ driver in WindowsWindows 中的 MongoDB C++ 驱动程序入门
【发布时间】:2015-09-27 10:51:48
【问题描述】:

尝试在 Windows 7 中使用C++ driver 建立一个简单的MongoDB 数据库连接。我将Visual C++ compiler 19 用于x8632-bit MongoDB 3.0.6Boost 1_59_0Mongo legacy 1.0.5 C++ driver

驱动使用命令编译OK

scons --cpppath=d:\boost_1_59_0 --libpath=d:\boost_1_59_0\stage\lib --msvc-host-arch=x86 install

程序是

#include <cstdlib>
#include <iostream>

using namespace std;
#include <WinSock2.h>
#include <windows.h>

#include "mongo/client/dbclient.h"

void run() {
  mongo::DBClientConnection c;
  c.connect("localhost");
}

int main() {
  try {
    run();
    std::cout << "connected ok" << std::endl;
  } catch( const mongo::DBException &e ) {
    std::cout << "caught " << e.what() << std::endl;
  }
  return EXIT_SUCCESS;
}

程序编译使用

cl /EHsc /I"c:\mongo-cxx-driver-legacy-1.0.5\build\install\include" /I"d:\boost_1_59_0" /DSTATIC_LIBMONGOCLIENT mdb.cpp c:\mongo-cxx-driver-legacy-1.0.5\build\install\lib\libmongoclient-s.lib /link /LIBPATH:"D:\boost_1_59_0\stage\lib" ws2_32.lib

但是当我运行程序时,得到错误信息

caught can't connect 无法初始化到localhost的连接,地址无效

server 运行正常,因为我可以通过shell 访问它,添加记录等。

这是我第一次编程MongoDB,我有点卡住了。有什么建议吗?

【问题讨论】:

    标签: c++ windows mongodb driver


    【解决方案1】:

    好的,问题解决了(感谢 stevepowell.ca/mongo-db-1.html)。以下是遇到此问题的其他人的答案:

    Windows 需要在建立连接之前初始化客户端。

    #include <cstdlib>
    #include <iostream>
    #include <WinSock2.h>
    #include <windows.h>
    #include <memory>
    
    #include "mongo/client/dbclient.h"
    
    using namespace mongo;
    using namespace std;
    
    void run() {
      mongo::client::initialize(); // this line is new
      mongo::DBClientConnection c;
      c.connect("localhost");
    }
    
    int main() {
      try {
        run();
        std::cout << "connected ok" << std::endl;
      } catch( const mongo::DBException &e ) {
        std::cout << "caught " << e.what() << std::endl;
      }
      return EXIT_SUCCESS;
    }
    

    我希望这已经在教程中!

    向上和向上。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 2017-05-09
    • 2016-03-13
    • 2012-03-04
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多