gpt4 book ai didi

c++ - Windows 中的 MongoDB C++ 驱动程序入门

转载 作者:可可西里 更新时间:2023-11-01 10:27:11 24 4
gpt4 key购买 nike

尝试在 Windows 7 中使用 C++ 驱动程序 建立一个简单的 MongoDB 数据库连接。我正在为 x8632 位 MongoDB 3.0.6Boost 1_59_0 使用 Visual C++ 编译器 19Mongo 遗留 1.0.5 C++ 驱动程序

驱动程序使用命令编译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

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

无法连接无法初始化到 localhost 的连接,地址无效

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

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

最佳答案

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

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

向前和向上。

关于c++ - Windows 中的 MongoDB C++ 驱动程序入门,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com