在Windows

时间:2015-09-27 10:51:49

标签: c++ windows mongodb driver

尝试使用MongoDB在Windows 7中设置简单的C++ driver数据库连接。我对Visual C++ compiler 19x8632-bit MongoDB 3.0.6Boost 1_59_0使用Mongo legacy 1.0.5 C++ driver

使用命令

编译驱动程序
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

但是当我运行程序时,会收到错误消息

捕获无法连接无法初始化与localhost的连接,地址无效

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

这是我第一次编程MongoDB而且我有点陷入困境。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

好的,问题解决了(感谢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;
}

我希望这已经在教程中了!

向上和向上。