本文整理汇总了C++中DBClientConnection类的典型用法代码示例。如果您正苦于以下问题:C++ DBClientConnection类的具体用法?C++ DBClientConnection怎么用?C++ DBClientConnection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBClientConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: prepareDatabase
/* ****************************************************************************
*
* prepareDatabase -
*/
static void prepareDatabase(std::string id, std::string type)
{
/* Set database */
setupDatabase();
DBClientConnection* connection = getMongoConnection();
/* We create one entity:
*
* - 'id', 'type' with four attributes
* A1: X
* A1: Y
* A2: Z
* A3: W
*/
BSONObj en1 = BSON("_id" << BSON("id" << id << "type" << type) <<
"attrs" << BSON_ARRAY(
BSON("name" << "A1" << "type" << "TA1" << "value" << "X") <<
BSON("name" << "A1" << "type" << "TA1bis" << "value" << "Y") <<
BSON("name" << "A2" << "type" << "TA2" << "value" << "Z") <<
BSON("name" << "A3" << "type" << "TA3" << "value" << "W")
)
);
connection->insert(ENTITIES_COLL, en1);
}
示例2: run
void run() {
DBClientConnection c;
c.connect("localhost"); //"192.168.58.1");
cout << "connected ok" << endl;
BSONObj p = BSON( "name" << "Joe" << "age" << 33 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Jane" << "age" << 40 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Abe" << "age" << 33 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Methuselah" << "age" << BSONNULL);
c.insert("tutorial.persons", p);
p = BSON( "name" << "Samantha" << "age" << 21 << "city" << "Los Angeles" << "state" << "CA" );
c.insert("tutorial.persons", p);
c.ensureIndex("tutorial.persons", fromjson("{age:1}"));
cout << "count:" << c.count("tutorial.persons") << endl;
auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj());
while( cursor->more() ) {
cout << cursor->next().toString() << endl;
}
cout << "\nprintifage:\n";
printIfAge(c, 33);
}
示例3: log
void SyncClusterConnection::_connect(const std::string& hostStr) {
log() << "SyncClusterConnection connecting to [" << hostStr << "]" << endl;
const HostAndPort host(hostStr);
DBClientConnection* c;
if (connectionHook) {
c = new DBClientConnection(
true, // auto reconnect
0, // socket timeout
[this, host](const executor::RemoteCommandResponse& isMasterReply) {
return connectionHook(host, isMasterReply);
});
} else {
c = new DBClientConnection(true);
}
c->setRequestMetadataWriter(getRequestMetadataWriter());
c->setReplyMetadataReader(getReplyMetadataReader());
c->setSoTimeout(_socketTimeout);
Status status = c->connect(host);
if (!status.isOK()) {
log() << "SyncClusterConnection connect fail to: " << hostStr << causedBy(status);
if (status == ErrorCodes::IncompatibleCatalogManager) {
// Make sure to propagate IncompatibleCatalogManager errors to trigger catalog manager
// swapping.
uassertStatusOK(status);
}
}
_connAddresses.push_back(hostStr);
_conns.push_back(c);
}
示例4: isSelf
bool isSelf(const HostAndPort& hostAndPort, ServiceContext* const ctx) {
// Fastpath: check if the host&port in question is bound to one
// of the interfaces on this machine.
// No need for ip match if the ports do not match
if (hostAndPort.port() == serverGlobalParams.port) {
std::vector<std::string> myAddrs = serverGlobalParams.bind_ips;
// If any of the bound addresses is the default route (0.0.0.0 on IPv4) it means we are
// listening on all network interfaces and need to check against any of them.
if (myAddrs.empty() ||
std::any_of(myAddrs.cbegin(), myAddrs.cend(), [](std::string const& addrStr) {
return HostAndPort(addrStr, serverGlobalParams.port).isDefaultRoute();
})) {
myAddrs = getBoundAddrs(IPv6Enabled());
}
const std::vector<std::string> hostAddrs =
getAddrsForHost(hostAndPort.host(), hostAndPort.port(), IPv6Enabled());
for (std::vector<std::string>::const_iterator i = myAddrs.begin(); i != myAddrs.end();
++i) {
for (std::vector<std::string>::const_iterator j = hostAddrs.begin();
j != hostAddrs.end();
++j) {
if (*i == *j) {
return true;
}
}
}
}
ctx->waitForStartupComplete();
try {
DBClientConnection conn;
conn.setSoTimeout(30); // 30 second timeout
// We need to avoid the isMaster call triggered by a normal connect, which would
// cause a deadlock. 'isSelf' is called by the Replication Coordinator when validating
// a replica set configuration document, but the 'isMaster' command requires a lock on the
// replication coordinator to execute. As such we call we call 'connectSocketOnly', which
// does not call 'isMaster'.
if (!conn.connectSocketOnly(hostAndPort).isOK()) {
return false;
}
if (auth::isInternalAuthSet() && !conn.authenticateInternalUser().isOK()) {
return false;
}
BSONObj out;
bool ok = conn.simpleCommand("admin", &out, "_isSelf");
bool me = ok && out["id"].type() == jstOID && instanceId == out["id"].OID();
return me;
} catch (const std::exception& e) {
warning() << "couldn't check isSelf (" << hostAndPort << ") " << e.what() << std::endl;
}
return false;
}
示例5: main
int main() {
try {
cout << "connecting to localhost..." << endl;
DBClientConnection c;
c.connect("localhost");
cout << "connected ok" << endl;
bo o = BSON( "hello" << "world" );
cout << "inserting..." << endl;
time_t start = time(0);
for( unsigned i = 0; i < 1000000; i++ ) {
c.insert("test.foo", o);
}
// wait until all operations applied
cout << "getlasterror returns: \"" << c.getLastError() << '"' << endl;
time_t done = time(0);
time_t dt = done-start;
cout << dt << " seconds " << 1000000/dt << " per second" << endl;
}
catch(DBException& e) {
cout << "caught DBException " << e.toString() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
示例6: run
void run(long time,short spo2,short pr,const char *deviceid)
{
DBClientConnection c;
c.connect(host);
BSONObj p = BSONObjBuilder().append(TIMESTAMP,(int)time).append(SPo2,spo2).append(PULSERATE,pr).append(DEVICEID,deviceid).obj();
c.insert(tablename, p);
}
示例7: mongoInit
Handle<Value> mongoInit(const Arguments& args){
char host[255];
if ( args.Length() > 0 && args[0]->IsString() ){
assert( args[0]->ToString()->Utf8Length() < 250 );
args[0]->ToString()->WriteAscii( host );
}
else {
strcpy( host , "127.0.0.1" );
}
DBClientConnection * conn = new DBClientConnection( true );
string errmsg;
if ( ! conn->connect( host , errmsg ) ){
return v8::ThrowException( v8::String::New( "couldn't connect" ) );
}
// NOTE I don't believe the conn object will ever be freed.
args.This()->Set( CONN_STRING , External::New( conn ) );
args.This()->Set( String::New( "slaveOk" ) , Boolean::New( false ) );
return v8::Undefined();
}
示例8: L
DBClientBase* DBConnectionPool::get(const string& host) {
boostlock L(poolMutex);
PoolForHost *&p = pools[host];
if ( p == 0 )
p = new PoolForHost();
if ( p->pool.empty() ) {
string errmsg;
DBClientBase *c;
if( host.find(',') == string::npos ) {
DBClientConnection *cc = new DBClientConnection(true);
if ( !cc->connect(host.c_str(), errmsg) ) {
delete cc;
uassert( (string)"dbconnectionpool: connect failed" + host , false);
return 0;
}
c = cc;
}
else {
DBClientPaired *p = new DBClientPaired();
if( !p->connect(host) ) {
delete p;
uassert( (string)"dbconnectionpool: connect failed [2] " + host , false);
return 0;
}
c = p;
}
return c;
}
DBClientBase *c = p->pool.front();
p->pool.pop();
return c;
}
示例9: kill_wrapper
inline void kill_wrapper(pid_t pid, int sig, int port){
#ifdef _WIN32
if (sig == SIGKILL || port == 0){
assert( handles.count(pid) );
TerminateProcess(handles[pid], 1); // returns failure for "zombie" processes.
}else{
DBClientConnection conn;
conn.connect("127.0.0.1:" + BSONObjBuilder::numStr(port));
try {
conn.simpleCommand("admin", NULL, "shutdown");
} catch (...) {
//Do nothing. This command never returns data to the client and the driver doesn't like that.
}
}
#else
int x = kill( pid, sig );
if ( x ){
if ( errno == ESRCH ){
}
else {
cout << "killFailed: " << errnoWithDescription() << endl;
assert( x == 0 );
}
}
#endif
}
示例10: getConn
void em_mongodb::queryincrement(std::string dbcoll,BSONElement last)
{
// int ret = MDB_FAIL_QUERY;
DBClientConnection* pconn = getConn();
if(!pconn)
return ;
mongo::Query cond = mongo::Query().sort("$natural");
// BSONElement last;// = minKey.firstElement();
while(1)
{
std::auto_ptr<mongo::DBClientCursor> cursor =
pconn->query(dbcoll,cond,0,0,0,QueryOption_CursorTailable|QueryOption_AwaitData);
while(1)
{
if(!cursor->more())
{
if(cursor->isDead())
{
break;
}
continue;
}
BSONObj obj = cursor->next();
last = obj["_id"];
//do something here...
incrementfunc(obj);
}
// cond = mongo::Query("_id"<<BSON("$gt"<<last)).sort("$natural");
}
boost::mutex::scoped_lock(m_iomux);
m_connpool[pconn] = false;
sem_post(&m_jobsem);
}
示例11: main
int main(void)
{
cout << "Welcome." << endl;
DBClientConnection conn;
string option;
string code;
string cmd;
conn.connect("localhost");
while(1){
cout << "> ";
getline(cin, cmd);
if(cmd.substr(0,4) == "quit"){
return 0;
}else if(cmd.substr(0,5) == "check"){
dealCheck(cmd,conn);
}else if(cmd.substr(0,3) == "set"){
dealSet(cmd, code, option);
//cout << code << option;
if(option == "-n" || option == "-N")
conn.update("HXTBBH.coupon", BSON("code" << code), BSON("$set" << BSON("status" << "unused")));
else if(option == "-y" || option == "-Y")
conn.update("HXTBBH.coupon", BSON("code" << code), BSON("$set" << BSON("status" << "used")));
}else{
cout << "synax error!" << endl;
}
}
return 0;
}
示例12: aggregateToDB
void FXtoBSON::aggregateToDB(const char & t,
DBClientConnection &c){
switch(t){
case 'h':
c.update(dbH, find(time0, 'h'),
BSON("$set" << BSON("quote" <<
aggregate('h'))),true);
Hour.setZero(60, 5);
break;
case 'd':
c.update(dbD, find(time0, 'd'),
BSON("$set" << BSON("quote" <<
aggregate('d'))), true);
Day.setZero(24, 5);
break;
case 'm':
c.update(dbM, find(time0, 'm'),
BSON("$set" << BSON("quote" <<
aggregate('m'))), true);
Month.setZero();
break;
case 'y':
c.update(dbY, find(time0, 'y'),
BSON("$set" << BSON("quote" <<
aggregate('y'))), true);
Year.setZero();
break;
}
}
示例13: mongoInsert
v8::Handle<v8::Value> mongoInsert(const v8::Arguments& args){
jsassert( args.Length() == 2 , "insert needs 2 args" );
jsassert( args[1]->IsObject() , "have to insert an object" );
DBClientConnection * conn = getConnection( args );
GETNS;
v8::Handle<v8::Object> in = args[1]->ToObject();
if ( ! in->Has( String::New( "_id" ) ) ){
v8::Handle<v8::Value> argv[1];
in->Set( String::New( "_id" ) , getObjectIdCons()->NewInstance( 0 , argv ) );
}
BSONObj o = v8ToMongo( in );
DDD( "want to save : " << o.jsonString() );
try {
conn->insert( ns , o );
}
catch ( ... ){
return v8::ThrowException( v8::String::New( "socket error on insert" ) );
}
return args[1];
}
示例14: main
int main(int argc,char* argv[]){
//check for file name
if (argc<2){
cout<<"NO FILENAME PROVIDED";
return 0;
}
//create object for input text file
ifstream input(argv[1]);
//connect to the mongo db localhost
DBClientConnection c;
c.connect("localhost");
XLog logParse("Parsing...");
logParse.start();
parseFile(input,c);
logParse.end();
XLog logScrub("Scrubbing...");
logScrub.start();
scrub(c);
logScrub.end();
XLog logOutput("Output to file...");
logOutput.start();
outputToFile(c);
logOutput.end();
return 0;
}
示例15: getCollFields
// finds the names of the document with the most fields in a collection
std::set<string> getCollFields(DBClientConnection& c, string db, string collection){
int longest;
// mongo fieldnames = sql column names
set<string> fieldnames;
// get the list of ODBC supported fields (columns) from collection.meta collection
// collection.meta should only contain one document
std::auto_ptr<mongo::DBClientCursor> cursor = c.query(db+"."+collection+".meta");
BSONObj d = cursor->next();
if (d.nFields() != 0){
longest = d.nFields();
d.getFieldNames(fieldnames);
}
// if no meta collection find collection with most fields
if (longest == 0) {
cursor = c.query(db+"."+collection);
while( cursor->more() ) {
// get next doc/row/tuple
BSONObj doc = cursor->next();
if(longest < doc.nFields()){
longest = doc.nFields();
doc.getFieldNames(fieldnames);
}
}
}
return fieldnames;
}