Esempio n. 1
0
void IfStatement::execute()
{
    if (cond->evaluate()) {
        cout << "TRUE " <<  endl;
        if (!truecode.empty()) {
            list<Statement *>::iterator it = truecode.begin();
            while (it != truecode.end()) {
                Statement *st = *it;
                //printf("StKind: %s\n",st->getSTR().c_str());
                st->execute();
                it++;
            }
            //truecode->execute();
        }
    }
    else{
        cout << "FALSE" <<  endl;
        if (!falsecode.empty()){
            list<Statement *>::iterator it = falsecode.begin();
            while (it != falsecode.end()) {
                Statement *st = *it;
                //printf("StKind: %s\n",st->getSTR().c_str());
                st->execute();
                it++;
            }
            //falsecode->execute();
        }
    }
}
Esempio n. 2
0
/*!
 * \brief   バージョン1にアップデート
 */
void SequenceLogServiceDB::updateVersion1() const throw(Exception)
{
    SLOG(CLS_NAME, "updateVersion1");
    Statement* stmt = nullptr;

    try
    {
        // バージョン情報テーブル作成
        query(
            "create table version_info("
            "    version int not null);");

        // バージョン登録
        stmt = newStatement();
        stmt->prepare("insert into version_info (version) values (1)");
        stmt->execute();

        delete stmt;
        stmt = nullptr;

        // アカウントテーブル作成
#if defined(USE_SQLITE)
        query(
            "create table user("
            "    id        integer     primary key autoincrement,"
            "    name      varchar     not null unique,"
            "    password  varchar     not null,"
            "    mail_addr varchar,"
            "    version   int         not null default 1,"
            "    admin     int         not null default 0);");
#else
        query(
            "create table user("
            "    id        int         primary key auto_increment,"
            "    name      varchar(20) not null unique,"
            "    password  varchar(64) not null,"
            "    mail_addr varchar(256),"
            "    version   tinyint     not null default 1,"
            "    admin     tinyint     not null default 0);");
#endif

        // 初期アカウント登録(パスワード:gols)
        stmt = newStatement();
        stmt->prepare("insert into user (name, password, admin) values ('slog', 'RrtQzcEv7FQ1QaazVN+ZXHHAS/5F/MVuDUffTotnFKk=', 1)");
        stmt->execute();
    }
    catch (Exception e)
    {
        SMSG(slog::DEBUG, "%s", e.getMessage());

        delete stmt;
        throw e;
    }

    delete stmt;
}
Esempio n. 3
0
int ODBCWrapper::insertBar(const int stmtId, unsigned int datetime, double *vals, const int size)
{
    int rv = 0;
    Statement *stmt = stmts[stmtId];
    if (!stmt) return MOB_INVALID_STMTID;
    //TODO: rewrite to use type-specific parameter binding method
    DataPointer *dps = (DataPointer *) malloc(sizeof(DataPointer) * (size + 1));

    SQL_TIMESTAMP_STRUCT ts;
    time_t tt = (time_t) datetime;
    TimestampPointer::timet2timestamp(&tt, &ts);
    dps[0] = TimestampPointer(&ts);
    for(int i = 0; i < size; i++)
        dps[i + 1] = DoublePointer(&vals[i]);
    try
    {
        stmt->bindParameters(dps, size + 1);
        rv = stmt->execute();
    }
    catch (ODBCException *e)
    {
        handleException(e);
        free(dps);
        return MOB_NG;
    }

    free(dps);
    return rv;
}
Esempio n. 4
0
int64_t Database::insert(const String &table, const Serializable &serializable)
{
	Statement dummy = prepare("SELECT * FROM `" + table + "` LIMIT 1");
	dummy.step();

	String columns;
	String values;

	int count = 0;
	for(int i=0; i<dummy.columnsCount(); ++i)
	{
		String name = dummy.name(i);
		if(name == "rowid" || name == "id")
			continue;

		if(count)
		{
			columns+= ',';
			values+= ',';
		}
		columns+= name;
		values+= "@" + name;

		++count;
	}

	dummy.finalize();

	String request = "INSERT OR REPLACE INTO `" + table + "` (" + columns + ") VALUES (" + values + ")";
	Statement statement = prepare(request);
	statement << serializable;
	statement.execute();	// unbound parameters will be interpreted as null

	return insertId();
}
Esempio n. 5
0
/*!
 * \brief   データベースバージョン取得
 *
 * \return  データベースバージョン
 */
int32_t SequenceLogServiceDB::getVersion() const
{
    SLOG(CLS_NAME, "getVersion");

    int32_t version = 0;
    Statement* stmt = nullptr;

    try
    {
        const char* sql = "select version from version_info";
        stmt = newStatement();
        stmt->prepare(sql);

        stmt->setIntResult(0, &version);

        stmt->bind();
        stmt->execute();
        stmt->fetch();
    }
    catch (Exception e)
    {
        // 初回起動時などテーブルが存在しない場合もあるので、
        // 例外が発生しても何もすることはない
        SMSG(slog::DEBUG, "%s", e.getMessage());
    }

    delete stmt;
    return version;
}
Esempio n. 6
0
int BillingInstance::SQL(std::string &query, std::vector<std::string> &params)
{
    if(_conn == NULL) {
        return 0;
    }
    int retval = 0;
    Statement *sth = NULL;

    try {
        sth = _conn->createStatement(query);

        sth->setAutoCommit(true);

        for(int i=0; i<params.size(); ++i) {
            sth->setString(i+1, params.at(i));
        }

        std::cerr << "Query execute" << std::endl;
        Statement::Status status = sth->execute();
    }
    catch (SQLException &sqlExcp)
    {
        std::cerr <<sqlExcp.getErrorCode() << " at " << __FILE__ << "/" << __LINE__ << ": " << sqlExcp.getMessage() << std::endl;
        retval = sqlExcp.getErrorCode();
    }

    if(sth != NULL) {
        _conn->terminateStatement(sth);
    }

    return retval;
}
Esempio n. 7
0
int main(int argc, char** argv)
{
	USE_NETWORK;
	using namespace sql;
	Statement *state;
	ResultSet *result;

	Connection *con = DbLib::instance().connect("tcp://127.0.0.1:3306", "root", "");
	state = con->createStatement();
	state->execute("use net_db");
	result = state->executeQuery("select * from g_user");
	//printf(" id user_id user_name level profession\n");
	printf("%7s%10s%20s%7s%10s\n", "id", "user_id", "user_name", "level", "role_id");
	while(result->next())
	{
		int64_t id		= result->getInt64("id");
		int user_id		= result->getInt("user_id");
		string user_name = result->getString("user_name");
		int level		= result->getInt("level");
		int profession	= result->getInt("role_id");

		printf(" %7d ", id);
		printf(" %10d ", user_id);
		printf(" %20s ", user_name.c_str());
		printf(" %7d ", level);
		printf(" %10d \n", profession);
	}

	delete state;
	delete con;

	system("pause");

	return 0;
}
bool AbstractConnection::rollback()
{
    bool rval = false;

    // save the reason for the rollback
    ExceptionRef reason = Exception::get();

    // attempt to do the rollback
    Statement* s = prepare("ROLLBACK");
    rval = (s != NULL) && s->execute() && s->reset();
    if(!rval)
    {
        ExceptionRef e = new Exception(
            "Could not rollback transaction.",
            "monarch.sql.Connection.TransactionRollbackError");
        if(!reason.isNull())
        {
            e->getDetails()["rollbackReason"] =
                Exception::convertToDynamicObject(reason);
        }
        Exception::push(e);
    }

    return rval;
}
Esempio n. 9
0
void runProgram(Program & program, EvalState & state) {
    int lineNumber = program.getFirstLineNumber();
    while (lineNumber != -1) {
        Statement * stmt = program.getParsedStatement(lineNumber);
        state.setCurrentLine(program.getNextLineNumber(lineNumber));
        stmt->execute(state);
        lineNumber = state.getCurrentLine();
    }
}
Esempio n. 10
0
/*
 * Function: runProgram
 * Usage: runProgram(program, context);
 * -------------------------------------------
 * Runs the program starting from the first line number.
 */
void runProgram(Program & program, EvaluationContext & context) {
    context.setCurrentLine(program.getFirstLineNumber());
    int programLine = context.getCurrentLine();
    while (programLine != -1) {
        Statement *stmt = program.getParsedStatement(programLine);
        context.setCurrentLine(program.getNextLineNumber(programLine)); // updates to line + 1
        stmt->execute(context);                         // unless controlled by IF, GOTO, or END
        programLine = context.getCurrentLine();
    }
}
Esempio n. 11
0
void BlockStatement::execute()
{
    list<Statement *>::iterator it = stList.begin();

    while (it != stList.end()) {
        Statement *st = *it;
        //printf("StKind: %s\n",st->getSTR().c_str());
        st->execute();
        it++;
    }
}
Esempio n. 12
0
void DataTest::testSession()
{
	Session sess(SessionFactory::instance().create("test", "cs"));
	sess << "DROP TABLE IF EXISTS Test", now;
	int count;
	sess << "SELECT COUNT(*) FROM PERSON", into(count), now;
	
	std::string str;
	Statement stmt = (sess << "SELECT * FROM Strings", into(str), limit(50));
	stmt.execute();
}
Esempio n. 13
0
void DatabaseSubsystem::getProcessParams(Session& session, ProcessPtr process)
{
    string paramName, paramValue;
    Statement stmt = (session <<
        "SELECT param_name, param_value FROM process_param WHERE process_id = ?",
        use(process->processID), range(0, 1), into(paramName), into(paramValue));
    while (!stmt.done()) {
        if (stmt.execute() == 1) {
            process->parameters[paramName] = paramValue;
        }
    }
}
Esempio n. 14
0
void WhileStatement::execute()
{
    while (cond->evaluate()){
      list<Statement *>::iterator it = block.begin();
      while (it != block.end()) {
          Statement *st = *it;
          //printf("StKind: %s\n",st->getSTR().c_str());
          st->execute();
          it++;
      }
    }
}
Esempio n. 15
0
void DatabaseSubsystem::getResponseLabels(Session& session,
                                          ResponsePtr& response)
{
    int objectID;
    int labelID;
    Statement stmt = (session <<
        "SELECT object_id, label_id FROM response_label WHERE response_id = ?",
        use(response->responseID), range(0, 1), into(objectID), into(labelID));
    while (!stmt.done()) {
        if (stmt.execute() == 1)
            response->labels[objectID] = labelID;
    }
}
Esempio n. 16
0
int main(int argc, char* argv[]) 
{
    //初始化连接,创建参数中maxSize一半的连接
    connpool.initPool("tcp://127.0.0.1:3306", "root", "123456", 100);

    Connection *con;
    Statement *state;
    ResultSet *result;
    con = connpool.GetConnection();
    for(int i = 0; i<2; i++)
    {
        state = con->createStatement();
        state->execute("use mysql");
 
        // 查询
        result = state->executeQuery("select host,user from user");
 
        // 输出查询
        while (result->next()) 
        {
            try{
                string user = result->getString("user"); 
                string name = result->getString("host");
                cout << user << " : " << name << endl;
            }catch(sql::SQLException& e){
                std::cout<< e.what() <<std::endl;
            }
        }

        result = state->executeQuery("select cust_id,cust_name from customers");
        while (result->next()) 
        {
            try{
                string user = result->getString("cust_id");
                string name = result->getString("cust_name");
                cout << user << " : " << name << endl;
            }catch(sql::SQLException& e){
              std::cout<< e.what() <<std::endl;
            }
        }
    
        std::cout << i << std::endl;
    
    }

    delete result;
    delete state;
    connpool.ReleaseConnection(con);

    return 0;
}
Esempio n. 17
0
File: driver.cpp Progetto: FuG/FSDB
/*
 * Overload Function: setup_test_table
 */
void setup_test_table(Connection *con, int numOfPocs, int sensorsPerPoc) {
    int i, j;
    Statement *stmt;
    PreparedStatement *pstmt;

    try {
        stmt = con->createStatement();
        stmt->execute("DROP TABLE IF EXISTS ParkingSpot");
        stmt->execute("CREATE TABLE ParkingSpot ("
                      "PocID int NOT NULL,"
                      "SensorID int NOT NULL,"
                      "SpotStatus int NOT NULL,"
                      "StartTime datetime DEFAULT NULL,"
                      "ExpireTime datetime DEFAULT NULL,"
                      "PRIMARY KEY (PocID, SensorID),"
                      "UNIQUE KEY LocationSensor_UNIQUE (PocID, SensorID))");
        delete stmt;

        pstmt = con->prepareStatement("INSERT INTO ParkingSpot (PocID, SensorID, SpotStatus) VALUES (?, ?, 0)");
        for(i = 0; i < numOfPocs; i++)
        {
            pstmt->setInt(1, i);
            for(j = 0; j < sensorsPerPoc; j++)
            {
                pstmt->setInt(2, j);
                pstmt->execute();
            }
        }
    } catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << " (function: " << __FUNCTION__ << ")" << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    delete pstmt;
}
Esempio n. 18
0
void processLine(string line, Program & program, EvalState & state) {
   TokenScanner scanner;
   scanner.ignoreWhitespace();
   scanner.scanNumbers();
   scanner.setInput(line);
//   Expression *exp = parseExp(scanner);
//   int value = exp->eval(state);
//   cout << value << endl;
//   delete exp;
   if (!scanner.hasMoreTokens()) {
       return;
   }
   string firstToken = toUpperCase(scanner.nextToken());
   if (firstToken == "RUN") {
       runProgram(program, state);
   }
   else if (firstToken == "QUIT") {
       exit(0);
   }
   else if (firstToken == "HELP") {
       dspHelp();
   }
   else if (firstToken == "CLEAR") {
       program.clear();
   }
   else if (firstToken == "LIST") {
       listCmd(program);
   }
   else if (firstToken == "INPUT" || firstToken == "PRINT" || firstToken == "LET") {
       scanner.saveToken(firstToken);
       Statement * stmt = parseStatement(scanner);
       stmt->execute(state);
       delete stmt;
   }
   else {
       int lineNumber = stringToInteger(firstToken);
       if (!scanner.hasMoreTokens()) {
           program.removeSourceLine(lineNumber);
       }
       else {
           int length = firstToken.length();
           string source = line.substr(length);
           program.addSourceLine(lineNumber, source);
           Statement * stmt = parseStatement(scanner);
           program.setParsedStatement(lineNumber, stmt);
       }
   }
}
Esempio n. 19
0
bool AbstractConnection::commit()
{
    bool rval = false;

    Statement* s = prepare("COMMIT");
    rval = (s != NULL) && s->execute() && s->reset();
    if(!rval)
    {
        ExceptionRef e = new Exception(
            "Could not commit transaction.",
            "monarch.sql.Connection.TransactionCommitError");
        Exception::push(e);
    }

    return rval;
}
Esempio n. 20
0
bool AbstractConnection::begin()
{
    bool rval = false;

    Statement* s = prepare("BEGIN");
    rval = (s != NULL) && s->execute() && s->reset();
    if(!rval)
    {
        ExceptionRef e = new Exception(
            "Could not begin transaction.",
            "monarch.sql.Connection.TransactionBeginError");
        Exception::push(e);
    }

    return rval;
}
Esempio n. 21
0
void run() {
 
    Connection *con;
    Statement *state;
    ResultSet *result;
	for(int i = 0; i<10000; i++){    
	con = connpool->GetConnection();
//    for(int i = 0; i<1000; i++)
//	{
		state = con->createStatement();
		state->execute("use mysql");
 
		// 查询
		result = state->executeQuery("select host,user from user");
 
		// 输出查询
		while (result->next()) 
		{
			try{
				string user = result->getString("user"); 
				string name = result->getString("host");
				cout << user << " : " << name << endl;
			}catch(sql::SQLException& e){
				std::cout<< e.what() <<std::endl;
			}
		}

		result = state->executeQuery("select cust_id,cust_name from customers");
		while (result->next()) 
		{
			try{
				string user = result->getString("cust_id");
				string name = result->getString("cust_name");
				cout << user << " : " << name << endl;
			}catch(sql::SQLException& e){
              std::cout<< e.what() <<std::endl;
			}
		}
	
		std::cout << i << std::endl;
	
//	}
	delete result;
    delete state;
    connpool->ReleaseConnection(con);
}}
Esempio n. 22
0
int main(int argc, char* argv[])
{
    init();

    std::string dbConnString = "user=root;password=;db=portabilidade;host=localhost;compress=true;auto-reconnect=true";

    Session ses(MySQL::Connector::KEY, dbConnString );


// esta implementacao esta correta e como deve ficar no programa
//    ses.begin();
//    ses << "INSERT INTO file VALUES ( 'meu teste' , '2108-02-10 00:00:00' , 9 , 'ofnf' ) " , now ; 
//    ses.commit();
//    ses.rollback();
     
// try {
//    ses.begin(); 
//    ses << "INSERT INTO meu VALUES ( 'meu teste' , '2108-02-10 00:00:00' , 9 , 'ofnf' ) " , now ;
//    ses.commit();
//}
//catch ( MySQL::MySQLException &e ) 
//{
//    cout << "	exception" << endl ;  
//}


    try {

    ses.begin();
    Statement stmt = ( ses << "INSERT INTO file VALUES('ariane',22333018 )" );
    stmt.execute();

    }catch ( MySQL::MySQLException &e )
    {
        cout << " exception" << endl ;
        ses.rollback();
    }

    //ses.commit();
    ses.rollback();

    MySQL::Connector::unregisterConnector();

    shutdown();
} // fim main
Esempio n. 23
0
int ODBCWrapper::selectToFetch(int stmtId)
{
    int rv = 0;
    Statement *stmt = stmts[stmtId];
    if (!stmt) return MOB_INVALID_STMTID;

    try
    {
        rv = stmt->execute(false);
    }
    catch (ODBCException *e)
    {
        handleException(e);
        return MOB_NG;
    }

    return rv;
}
Esempio n. 24
0
void DatabaseSubsystem::getAvailableFeatures(Session& session,
    const map<int, int>& clObjMap, FeatureSet& featureSet)
{
    int ddType;
    string featureName;
    double featureParam1, featureParam2, featureParam3;

    featureSet.clear();

    ostringstream clObjIDs;
    for (map<int, int>::const_iterator itr = clObjMap.begin();
         itr != clObjMap.end(); ++itr)
    {
        if (itr != clObjMap.begin()) {
            clObjIDs << ",";
        }
        clObjIDs << itr->first;
    }

    Statement stmt = (session <<
        "SELECT DISTINCT "
        "  data_descriptor.type, data_feature.feature_name, "
        "  data_feature.feature_param1, data_feature.feature_param2, "
        "  data_feature.feature_param3  "
        "FROM data_feature INNER JOIN data_descriptor "
        "ON (data_feature.descr_id = data_descriptor.descr_id) "
        "WHERE data_descriptor.descr_id IN ("
        "  SELECT descr_id FROM classification_object_data WHERE object_id IN ("
        << clObjIDs.str()
        << "))",
        range(0, 1),
        into(ddType), into(featureName), into(featureParam1), 
        into(featureParam2), into(featureParam3));

    while (!stmt.done()) {
        if (stmt.execute() == 1) {
            featureSet.add(FeatureDescriptor(featureName,
                (DataDescriptor::Type) ddType, featureParam1, featureParam2, 
                featureParam3));
        }
    }
}
Esempio n. 25
0
int ODBCWrapper::copyRates(const int stmtId, RateInfo *rates, const int size, const int start, const int end)
{
    int rv = 0;
    Statement *stmt = stmts[stmtId];
    if (!stmt) return MOB_INVALID_STMTID;
    if (start < 0 || end > size || start > end) return MOB_NG;

    for (int i = start; i < end; i++)
    {
        SQL_TIMESTAMP_STRUCT ts;
        time_t tt = (time_t) rates[i].ctm;
        TimestampPointer::timet2timestamp(&tt, &ts);
        DataPointer dps[6] =
        {
            TimestampPointer(&ts),
            DoublePointer(&rates[i].open),
            DoublePointer(&rates[i].high),
            DoublePointer(&rates[i].low),
            DoublePointer(&rates[i].close),
            DoublePointer(&rates[i].vol)
        };
        try
        {
            //TODO: rewrite to use type-specific parameter binding method
            stmt->bindParameters(dps, 6);
            rv += stmt->execute();
        }
        catch (ODBCException *e)
        {
            handleException(e);
            return MOB_NG;
        }
    }

    return rv;
}
Esempio n. 26
0
DataSet DatabaseSubsystem::getDataSet(ResponsePtr response,
                                      const FeatureSet& featureSet)
{
    RWLock::ScopedLock lock(_dbLock);

    DataSet result;
    Session session = getSession();
    session.begin();

    // This map counts the number of values for each feature.
    map<FeatureDescriptor, int> dataCount;

    for (map<int, int>::const_iterator labelItr = response->labels.begin();
        labelItr != response->labels.end(); ++labelItr)
    {
        int ddType;
        string featureName;
        double featureParam1, featureParam2, featureParam3;
        double featureValue;

        DataPoint point;
        point.objectID = labelItr->first;
        point.classLabel = labelItr->second;

        Statement stmt = (session <<
            "SELECT data_descriptor.type, data_feature.feature_name, "
            "  data_feature.feature_param1, data_feature.feature_param2, "
            "  data_feature.feature_param3, data_feature.feature_value "
            "FROM data_feature INNER JOIN data_descriptor "
            "ON (data_feature.descr_id = data_descriptor.descr_id) "
            "WHERE data_descriptor.descr_id IN ("
            "  SELECT descr_id FROM classification_object_data "
            "  WHERE object_id = ?"
            ")",
            use(labelItr->first),
            range(0, 1),
            into(ddType), into(featureName), 
            into(featureParam1), into(featureParam2), into(featureParam3), 
            into(featureValue)
        );

        while (!stmt.done()) {
            if (stmt.execute() == 1)
            {
                FeatureDescriptor featureDescr(featureName,
                    (DataDescriptor::Type) ddType, featureParam1, 
                    featureParam2, featureParam3);
                if (featureSet.has(featureDescr)) {
                    point.components[featureDescr] = featureValue;
                    ++dataCount[featureDescr];
                }
            }
        }

        // Reject "empty" data points.
        if (!point.components.empty())
            result.push_back(point);
    }
    session.commit();

    if (dataCount.size() > 0) {
        map<FeatureDescriptor, int>::const_iterator itr = dataCount.begin();
        int firstCount = itr->second;
        for (; itr != dataCount.end(); ++itr) {
            if (itr->second != firstCount) {
                throw Poco::RuntimeException("Feature count mismatch: " +
                    itr->first.toString());
            }
        }
    }

    return result;
}
Esempio n. 27
0
bool DatabaseClient::execute(SqlExecutableRef& se, Connection* c)
{
   bool rval = false;

   if(se.isNull())
   {
      // typical usage will involve generating an SQL executable and then
      // passing it to this method ... the generation might result in a
      // NULL SQL executable which would be passed here and caught for
      // convenience ... if that's the case a relevant exception is already
      // set -- for the degenerate/unusual case nothing is set yet so we set
      // something here
      if(!Exception::isSet())
      {
         ExceptionRef e = new Exception(
            "Could not execute SQL. SqlExecutable is NULL.",
            DBC_EXCEPTION ".NullSqlExecutable");
         Exception::set(e);
      }
   }
   else
   {
      // FIXME: this is for mysql only, see FIXME below
      if(se->returnRowsFound)
      {
         size_t i = se->sql.find("SELECT ");
         if(i != string::npos)
         {
            se->sql.insert(i + 7, "SQL_CALC_FOUND_ROWS ");
         }
      }

      if(mDebugLogging)
      {
         MO_CAT_DEBUG_DATA(MO_SQL_CAT,
            "SqlExecutable:\n"
            "sql: %s\n"
            "write: %s\n"
            "params: %s\n"
            "columnSchemas: %s\n"
            "whereFilter: %s\n",
            se->sql.c_str(),
            se->write ? "true" : "false",
            JsonWriter::writeToString(se->params, false, false).c_str(),
            JsonWriter::writeToString(se->columnSchemas, false, false).c_str(),
            JsonWriter::writeToString(se->whereFilter, false, false).c_str());
      }

      // get a connection from the pool if one wasn't passed in
      Connection* conn = (c == NULL) ?
         (se->write ? getWriteConnection() : getReadConnection()) : c;
      if(conn != NULL)
      {
         // prepare statement, set parameters, and execute
         Statement* s = conn->prepare(se->sql.c_str());
         rval = (s != NULL) && setParams(s, se->params) && s->execute();

         // if we wrote to the database, get affected rows and last insert ID
         if(rval && se->write)
         {
            s->getRowsChanged(se->rowsAffected);
            se->lastInsertRowId = s->getLastInsertRowId();
         }
         // else we read, so get row results
         else if(rval && !se->result.isNull())
         {
            // get results as an array
            if(se->result->getType() == Array)
            {
               // FIXME: we intentionally do not check rval in this while()
               // loop right now because there are some issues where if
               // if we don't retrieve the entire result set (fetch each row)
               // then we run into problems -- this needs to be double checked
               // so we can handle this case better

               // iterate over rows
               int index = 0;
               Row* r;
               while((r = s->fetch()) != NULL)
               {
                  // pull out data
                  DynamicObject& row = se->result[index++];
                  rval = getRowData(se->columnSchemas, r, row);
               }

               // save number of rows retrieved
               se->rowsRetrieved = se->result->length();
            }
            // get results as a single map
            else
            {
               Row* r = s->fetch();
               if(r == NULL)
               {
                  // the value doesn't exist
                  se->rowsRetrieved = 0;
               }
               else
               {
                  // row found, pull out data
                  se->rowsRetrieved = 1;
                  rval = getRowData(se->columnSchemas, r, se->result);

                  // finish out result set
                  s->fetch();
               }
            }

            // get total rows found if requested
            if(rval && se->returnRowsFound)
            {
               // FIXME: we want to abstract this better but aren't sure how
               // we want to yet ... this implementation is mysql only ...
               // in sqlite3 you do a select without a limit and then only
               // return the rows up to the limit and then keep counting
               // past it with fetch() ... in postgresql you have to do a
               // SELECT COUNT(*) as total within a transaction

               // select found rows
               const char* sql = "SELECT FOUND_ROWS() AS total";
               Statement* statement = conn->prepare(sql);
               rval = (statement != NULL) && statement->execute();
               if(rval)
               {
                  // fetch total row
                  Row* row = statement->fetch();
                  if(row != NULL)
                  {
                     row->getUInt64("total", se->rowsFound);
                  }
                  else
                  {
                     ExceptionRef e = new Exception(
                        "Could not get the total number of found rows.",
                        DBC_EXCEPTION ".GetFoundRowsFailed");
                     Exception::push(e);
                     rval = false;
                  }
               }
            }
         }

         // close connection if it was not passed in
         if(c == NULL)
         {
            conn->close();
         }
      }
   }

   return rval;
}
Esempio n. 28
0
void now(Statement& statement)
{
    statement.execute();
}
int main(int argc, char** argv) {
  detector sileneDetector("flower.xml", "../BagOfWords/vocabulary.xml", "../BagOfWords/silene.xml");

  vector<string> positive;
  vector<string> negative;

  Driver* driver = get_driver_instance();
  Connection* con = driver->connect("tcp://localhost:3306", "jamie", "luciDMoss");
  Statement* stmt = con->createStatement();
  stmt->execute("USE luminous_db;");

  // Fetch positives from db.
  ResultSet* positiveResults = stmt->executeQuery("SELECT FileName, Location FROM observations WHERE UseForTraining=false AND isSilene=true;");
  while (positiveResults->next()) {
    positive.push_back(positiveResults->getString("Location") + "/" + positiveResults->getString("FileName"));
  }
  delete positiveResults;

  // Fetch negatives from db.
  ResultSet* negativeResults = stmt->executeQuery("SELECT FileName, Location FROM observations WHERE UseForTraining=false AND isSilene=false;");
  while (negativeResults->next()) {
    negative.push_back(negativeResults->getString("Location") + "/" + negativeResults->getString("FileName"));
  }
  delete negativeResults;

  
  // Initialize some variables for statistics later.
  int total = positive.size() + negative.size();
  int expected_positive = positive.size();
  int expected_negative = negative.size();
  int actual_positive = 0;
  int actual_negative = 0;
  int false_positive = 0;
  int false_negative = 0;
  
  for (int i=0; i<positive.size(); i++) {
    cout << positive[i] << endl;
    Mat image = imread(positive[i], CV_LOAD_IMAGE_COLOR);
    
    if (sileneDetector.isThisSilene(image)) {
      actual_positive += 1;
    } else {
      cout << "False negative: " << positive[i] << endl;
      false_negative += 1;
    }
    cout << "-------------------------" << endl;
  }

  for (int i=0; i<negative.size(); i++) {
    cout << negative[i] << endl;
    Mat image = imread(negative[i], CV_LOAD_IMAGE_COLOR);
    if (sileneDetector.isThisSilene(image)) {
      cout << "False positive: " << negative[i] << endl;
      false_positive += 1;
    } else {
      actual_negative += 1;
    }
    cout << "-------------------------" << endl;
  }
  
  int correct = actual_positive + actual_negative;
  int incorrect = false_positive + false_negative;
  
  cout << "total: " << total << endl;
  cout << "expected_positive: " << expected_positive << endl;
  cout << "expected_negative: " << expected_negative << endl;
  cout << "actual_positive: " << actual_positive << endl;
  cout << "actual_negative: " << actual_negative << endl;
  cout << "false_positive: " << false_positive << endl;
  cout << "false_negative: " << false_negative << endl;
  cout << "correct: " << correct << endl;
  cout << "incorrect: " << incorrect << endl;

  //cout << "Correctly identified: " << correct << " " << double(correct)/total << endl;
  //cout << "False Positives: " << false_positive << " " << double(false_positive)/total << endl;
  //cout << "False Negatives: " << false_negative << " " << double(false_negative)/total << endl;
  //cout << "Percent of NotSilene incorrectly identified: " << double(false_positive)/expected_positive << endl;
  //cout << "Percent of Silene incorrectly identified: " << double(false_negative)/expected_negative << endl;

  delete stmt;
  delete con;
}
Esempio n. 30
0
/*初始化*/
int dzpkInit()
{
    //荷官容器第0位填充
	DEALER_T init_dealer;
	init_dealer.pDealer = new dealer();
	init_dealer.pDealer->dealer_id = 0;



    //数据库连接池初始化
    Connection *con = connpool->GetConnection();
	if(con == NULL)
	{
		WriteLog(40008,"get db connection fail \n");
        exit(1);
	}
        Statement *state =con->createStatement();//获取连接状态
        state->execute("use dzpk");//使用指定的数据库
        string  sql="select * from tbl_room_mst order by small_blind asc;";

        string  sql_up="update tbl_room_mst set current_seat_person=0,current_sideline_person=0 where room_id >0;";
                // UPDATE
                state->execute(sql_up);

        // 查询
        ResultSet *result = state->executeQuery(sql);

        vector<room>  room_list;
        // 输出查询
        while (result->next()) {
            room rm;
            rm.room_id = result->getInt("room_id");
            rm.room_name = result->getString("room_name");
            rm.current_seat_person = result->getInt("current_seat_person");
            rm.current_sideline_person = result->getInt("current_sideline_person");
            rm.small_blind = result->getInt("small_blind");
			rm.charge_per = result->getInt("charge_per");
            rm.minimum_bring = result->getString("minimum_bring");
            rm.maximum_bring = result->getString("maximum_bring");
            rm.room_seat_number = result->getInt("room_seat_number");
            rm.room_type= result->getInt("room_type");
            rm.room_level_st = result->getInt("room_level_st");
            rm.room_level_nd = result->getInt("room_level_st");
            rm.bet_time = result->getInt("bet_time");
            rm.host_ip = result->getString("host_ip");
            rm.port = result->getString("port");
            rm.before_chip = result->getString("before_chip");

            room_list.push_back(rm);
        }
        if(result)
        {
            delete result;
            result = NULL;
        }
        delete state;//删除连接状态
        connpool->ReleaseConnection(con);//释放当前连接

        int nRoomCount = 0;

        for(unsigned int i=0;i< room_list.size();i++)
	{
	    DEALER_T init_dealer;
	    init_dealer.pDealer = new dealer();

            room rm = room_list.at(i);

            init_dealer.pDealer->dealer_id = rm.room_id;
            init_dealer.pDealer->small_blind = rm.small_blind;
			init_dealer.pDealer->charge_per = rm.charge_per;
            init_dealer.pDealer->min_buy_chip = atoi(rm.minimum_bring.c_str());
            init_dealer.pDealer->max_buy_chip = atoi(rm.maximum_bring.c_str());
            init_dealer.pDealer->before_chip = atoi(rm.before_chip.c_str());
            init_dealer.pDealer->room_seat_num = rm.room_seat_number;
            init_dealer.pDealer->max_follow_chip = atoi(rm.maximum_bring.c_str());
            init_dealer.pDealer->bet_time = rm.bet_time;
            init_dealer.pDealer->room_type = rm.room_type;
            init_dealer.pDealer->room_level_st = rm.room_level_st;
            init_dealer.pDealer->room_level_nd = rm.room_level_nd;
            init_dealer.pDealer->room_name= rm.room_name +"["+ itoa(rm.room_id,10)+"]";

            int desk_cd[5]={ 0,0,0,0,0 };
            memcpy(init_dealer.pDealer->desk_card,desk_cd,sizeof(desk_cd));//数组拷贝
            //初始化一副牌,百位代表了花色4、3、2、1 分别代表 黑 红 梅 方 , 十位和个位代表牌面2~A
            int cards[52] ={102,103,104,105,106,107,108,109,110,111,112,113,114,202,203,204,205,206,207,208,209,210,211,212,213,214,302,303,304,305,306,307,308,309,310,311,312,313,314,402,403,404,405,406,407,408,409,410,411,412,413,414};
            //先发手牌,再发公共牌
            //int cards[52] ={403,413,405,302,113,308,108,305,207,111,103,312,210,111,414,114,110,306,104,307,211,204,205,212,213,214,302,303,304,305,306,307,308,309,310,311,312,313,314,402,403,404,405,406,407,408,409,410,411,412,413,414};

            memcpy(init_dealer.pDealer->card_dun,cards,sizeof(cards));//数组拷贝,初始化荷官手中的牌

            init_dealer.pDealer->step=0;
            init_dealer.pDealer->all_desk_chips=0;
            init_dealer.pDealer->turn = 0;
            init_dealer.pDealer->seat_small_blind = 0;
            init_dealer.pDealer->seat_big_blind = 0;
            init_dealer.pDealer->look_flag = 0;
            init_dealer.pDealer->add_chip_manual_flg = 0;
            init_dealer.pDealer->current_player_num =0;
            init_dealer.pDealer->nRing =0;
            init_dealer.pDealer->nActionUserID=0;
            init_dealer.pDealer->nCpsRecordID=0;
            init_dealer.pDealer->nTurnMinChip=0;
            init_dealer.pDealer->nTurnMaxChip=0;
            init_dealer.pDealer->seat_bank =0;
            init_dealer.pDealer->seat_small_blind =0;
            init_dealer.pDealer->seat_big_blind =0;
            init_dealer.pDealer->nStepOver =0;

            if(nRoomCount == 0)
            {
                DEALER_T init_dealerTemp;
                init_dealerTemp.pDealer = new dealer();
                *init_dealerTemp.pDealer = *init_dealer.pDealer;
                init_dealerTemp.pDealer->dealer_id = 1;

                g_dzpkDealers.Insert(init_dealerTemp.pDealer->dealer_id,(void*)&init_dealerTemp,sizeof(DEALER_T));
                dealers_vector.push_back(init_dealerTemp.pDealer);
            }

            dealers_vector.push_back(init_dealer.pDealer);
	        g_dzpkDealers.Insert(init_dealer.pDealer->dealer_id,(void*)&init_dealer,sizeof(DEALER_T));
            nRoomCount++;
        }

	for(int i=0;i<(int)dealers_vector.size();i++)
	{
		dealers_vector[i]->nVecIndex = i;
	}

        //读取等级-经验值系统
        Connection *con1 = connpool->GetConnection();
        Statement *state1 =con1->createStatement();//获取连接状态
        state1->execute("use dzpk");//使用指定的数据库
        string  sql1="select * from tbl_level_exp_mst;";
        // 查询
        ResultSet *result1 = state1->executeQuery(sql1);

        // 输出查询
        while (result1->next()) {
            level_system lm;
            lm.ex_id = result1->getInt("ex_id");
            lm.level = result1->getInt("level");
            lm.level_title = result1->getString("level_title");
            string slevel_upgrade =result1->getString("exp_upgrade");
            lm.exp_upgrade = atol(slevel_upgrade.c_str());
            string sexp_total =result1->getString("exp_total");
            lm.exp_total = atol(sexp_total.c_str());
            level_list.push_back(lm);
        }
        if(result1)
        {
            delete result1;
            result1 = NULL;
        }
        delete state1;//删除连接状态
        connpool->ReleaseConnection(con1);//释放当前连接


        /*清除用户在房间标识*/
        dzpkDbClearUserRoomMark();

#ifdef CPS_TEXT
        dealer *pRoom = DzpkGetRoomInfo(1030);
        if(pRoom)
        {
            pRoom->room_type = 5;
        }

        CPS_RECORD_T _Record;
        _Record.nRecordID = 100;
        _Record.nType = 5;
        _Record.nStartTime = time(NULL) + 20;
        _Record.nStart = 0;
        _Record.nArryRoomIndex= 0;
        _Record.nCurSmallBlind = 50;
        _Record.nInitHandChip= 1000;
        _Record.pMutex = new CMutex();
        _Record.nLastAddBlindTime = _Record.nStartTime;
        _Record.nAddBlind = CPS_ADD_ONE_BLIND;
        _Record.nAddBlindTime = CPS_ADD_BLIND_TIME;
        _Record.nRecordUserCount = 0;

        CpsInsertRecord(_Record.nRecordID,&_Record,sizeof(_Record));


        SAFE_HASH_LIST_T *pList = CpsRecordGetList();
        if(pList)
        {
            if(pList->nSize > 0)
            {
                CPS_RECORD_T *p = (CPS_RECORD_T *)pList->pTable[0];
            }
            CpsRecordFreeList(pList);
        }

#endif

	return 0;
}