Пример #1
0
	PlayerInfo * db_findPlayerInfo(Connection *conn, const std::string &sql)
	{
		PlayerInfo *info = NULL;
		Statement *stmt = conn->createStatement();
		ResultSet *res = stmt->executeQuery(sql.c_str());

		if (res->next())
		{
			info = new PlayerInfo;

			info->user_id = res->getUInt("user_id");
			std::string user_name = res->getString("user_name");
			size_t size = user_name.size() < MAX_NAME ? user_name.size() : MAX_NAME;
			memcpy(info->user_name, user_name.c_str(), size);
			info->level = res->getInt("level");
			info->gender = res->getInt("gender");
			info->role_id = res->getInt("role_id");
			info->scene_id = res->getInt("scene_id");
			info->x = res->getInt("x");
			info->y = res->getInt("y");
			std::string user_pwd = res->getString("user_pwd");
			size = user_pwd.size() < MAX_PWD ? user_pwd.size() : MAX_PWD;
			memcpy(info->user_pwd, user_pwd.c_str(), size);
		}

		delete stmt;
		delete res;
		return info;
	}
Пример #2
0
void HMMDataSet::read(int idAction){ 
    openMysqlSession();
    
    cout<<"Reading HMMData for action:"<<idAction<<endl;
    this->idAction=idAction;
    
    ResultSet *resSet;
    PreparedStatement *prep_stmt;

    /* create a statement object */
    prep_stmt = con -> prepareStatement("SELECT * FROM `HMMDataSet` WHERE `compression_rate`=? AND `num_clusters`=? AND `id_action`=?");
    prep_stmt->setInt(1, compressionRate);  
    prep_stmt->setInt(2, numClusters);  
    prep_stmt->setInt(3, idAction);    
    resSet = prep_stmt->executeQuery();

    while (resSet->next()) {
        std::stringstream state_trans(resSet->getString("state_trans"));
        std::stringstream initial_state_dist(resSet->getString("initial_state_dist"));
        std::stringstream obs_prob_dist(resSet->getString("obs_prob_dist"));
        std::stringstream cluster_distribution(resSet->getString("cluster_distribution"));
        
        stateTrans.resize(numStates, vector<double>(numStates, 0));
        initialStateDist.resize(numStates, 0);
        obsProbDist.resize(numStates, vector<double>(numStates,0));
        clustDist.resize(numStates);
       
        for (int i = 0; i < numClusters; i++) {
            for (int j = 0; j < numClusters; j++) {
                state_trans >> stateTrans[i][j];
            }
        }
         
        for (int j = 0; j < numClusters; j++) {
            initial_state_dist >> initialStateDist[j];
        }
           
        for (int i = 0; i < numClusters; i++) {
            for (int j = 0; j < numClusters; j++) {
                obs_prob_dist>> obsProbDist[i][j];
            }
        }       
             
        for (int j = 0; j < numClusters; j++) {
            ClusterDistribution cluster;           
            cluster_distribution >> cluster.mean.idCluster;            
             cluster.mean.center.resize(Vector_Size);
            for (int k = 0; k < Vector_Size; k++) {
                cluster_distribution >> cluster.mean.center[k];
            }             
            cluster_distribution >> cluster.standardDeviation;           
            clustDist.push_back(cluster);
        }        
    }
    
    delete resSet;
    delete prep_stmt;
    closeMysqlSession();
    
}
Пример #3
0
int ChargeBusiness::QueryOrder(TopupInfo *topupInfo){
    int ret = 0;
    Statement *stmt = NULL;
    try{
        stmt = conn->createStatement(SQL_CREATE_ORDER);
        string tbOrderNo = topupInfo->qs_info.tbOrderNo;
    fprintf(stderr, "ChargeBusiness::QueryOrder %s\n", tbOrderNo.c_str());
        stmt->setString(1, tbOrderNo);
        ResultSet *rs = stmt->executeQuery();
        while(rs->next())
        {
            topupInfo->qs_info.tbOrderNo = rs->getString(1);
            topupInfo->qs_info.coopOrderNo = rs->getString(2);
            topupInfo->status = (OrderStatus)rs->getInt(3);
            string ts = rs->getString(4);
            trans_time(ts, topupInfo->update_time);
            ret++;
        }
        conn->terminateStatement(stmt);
    }catch(SQLException &sqlExcp){
        HandleException(sqlExcp);
        ret = -1;
    }catch(std::exception &e){
        HandleException(e);
        ret = -1;
    }
    Finish();
    if(stmt)
        conn->terminateStatement(stmt);
    return ret;
}
Пример #4
0
//through the product info get the best channel to create order
//@return the channel num
int ChargeBusiness::SelectBestChannel(int value, int province, int op, vector<ChannelInfo>& channels){
    int ret = 0;
    Statement *stmt = NULL;
    try{
        stmt = conn->createStatement(SQL_SELECT_CHANNEL);
        stmt->setInt(1, value);         //product value
        stmt->setInt(2, province);      //provice of product
        stmt->setInt(3, op);            //operator of product
        ResultSet *rs = stmt->executeQuery();
        while(rs->next())
        {
            ChannelInfo channel;
            channel.channelId = rs->getInt(1);               //channel id
            //channel.channelName = rs->getString(2);          //channel name
            channel.sname = rs->getString(2);                //short name
            channel.priority = rs->getInt(3);                //priority
            channel.repeat = rs->getInt(4);                  //repeat times
            channel.discount = rs->getFloat(5);              //discount of product
            channel.interfaceName = rs->getString(6);        //the interface of channel,through it to find the class to handle order
            channel.pid = rs->getString(7);                  //the product id given by channel
            channel.private_key = rs->getString(8);          //the private key given by channel
            channel.query_interval = rs->getInt(9);          //query order interval
            channels.push_back(channel);
            ret++;
        }
        stmt->closeResultSet(rs);
    }catch(std::exception &e){
        HandleException(e);
        ret = -1;
    }
    Finish();
    if(stmt)
        conn->terminateStatement(stmt);
    return ret;
}
Пример #5
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;
}
void AdminServlet::handleGet(HttpRequest* request, HttpResponse* response) {
	ResultSet* result;

	try {
		result = ServerDatabase::instance()->executeQuery("SELECT DISTINCT account_id, ip, COUNT(*) FROM account_ips WHERE timestamp >= DATE_SUB(timestamp, INTERVAL 1 DAY) GROUP BY ip HAVING COUNT(*) > 2 ORDER BY COUNT(*) DESC");
	} catch (DatabaseException& e) {
		response->println(e.getMessage());
		return;
	}

	response->println("HTTP/1.1 200 OK");
	response->println("Content-Type: text/html");
	response->println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
	response->println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
	response->println("	<head>");
	response->println("	 <title>SWGEmu Multiple Account Administration</title>");
	response->println("	 <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />");
	response->println("	 <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" />");
	response->println("	</head>");
	response->println("	<body>");
	response->println("  <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
	response->println("   <caption>Suspect List</caption>");
	response->println("   <tr>");
	response->println("    <th>IP Address</th>");
	response->println("    <th>Count</th>");
	response->println("   </tr>");

	if (result->size() > 0) {
		while (result->next()) {
			String ip = "<a href=\"http://ip-lookup.net/?ip=";
			ip += String::valueOf(result->getString(1));
			ip += "\">";
			ip += String::valueOf(result->getString(1));
			ip += "</a>";
			response->println("   <tr>");
			response->println("    <td>" + ip + "</td>");
			response->println("    <td>" + String::valueOf(result->getInt(2)) + "</td>");
			response->println("   <tr>");
		}
	} else {
		response->println("   <tr>");
		response->println("    <td>No suspects found.</td>");
		response->println("   <tr>");
	}

	delete result;
	result = NULL;

	response->println("	</body>");
	response->println("</html>");
}
Пример #7
0
//验证用户微信号
int ChargeBusiness::VerifyWeixin(string userId, string openId){
    Statement *stmt = NULL;
    int ret = 0;
    try{
        stmt = conn->createStatement(QUERY_USER_SQL);
        stmt->setString(1, userId);
        ResultSet *rs = stmt->executeQuery();
        string user_open_id;
        int id = -1;
        while(rs->next())
        {
            id = rs->getInt(1);
            user_open_id = rs->getString(2);
        }
        if(id == -1){
            ret = 1;
        }else if(user_open_id.empty()){
            conn->terminateStatement(stmt);
            stmt = conn->createStatement(VERIFY_SQL);
            stmt->setString(1, openId);
            stmt->setString(2, userId);
            stmt->executeUpdate();
        }else{
            ret = 2;
        }
        
    }catch(SQLException &sqlExcp){
        HandleException(sqlExcp);
    }catch(std::exception &e){
        HandleException(e);
    }   
    if(stmt)
        conn->terminateStatement(stmt);
    return ret;
}
Пример #8
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;
}
Пример #9
0
///ret = 2 no such product
///ret = 1 exception not find product
int ChargeBusiness::GetTmallProduct(string productId, Product &product){
    int ret = 0;
    Statement *stmt = NULL;
    try{
        //初始化数据库连接
        stmt = conn->createStatement(SQL_QUERY_PRODUCT);
        stmt->setString(1, productId);
        ResultSet *rs = stmt->executeQuery();
        while (rs->next())
        {
            product.productId = rs->getString(1);
            product.provinceId = rs->getInt(2);
            product.price = rs->getInt(3);
            product.op = rs->getInt(4);    
        }
        stmt->closeResultSet(rs);
        if(product.productId.empty() || product.provinceId == 0){
            ret = 2;
        }
    }
    catch(std::exception &e)
    {
        HandleException(e);
        ret = 1;
    }
    Finish();
    if(stmt)
        conn->terminateStatement(stmt);
    return ret;
}
Пример #10
0
bool TEST_CONNECTION(){
	GlobalConfig *gconf = GlobalConfig::Instance();
    if(gconf == NULL || !gconf->Init("../conf/topup.ini")){
	       exit(EXIT_FAILURE);
    }
	ConnectionManager* conn_manager  = ConnectionManager::Instance();
    printf("user:%s\tpasswd:%s\n", gconf->s_db_userName.c_str(), gconf->s_db_passWord.c_str());
    if(conn_manager == NULL || !conn_manager->Init(gconf->s_db_userName,                                                                                                                    
	             gconf->s_db_passWord, gconf->s_db_connString,
	             gconf->n_max_connection, gconf->n_min_connection,
	               gconf->n_inc_connection)){
	       exit(EXIT_FAILURE);
    }	
	Connection *conn = conn_manager->CreateConnection();
	Statement *stmt = conn->createStatement("SELECT ID,ZONE,VALUE,OPERATOR FROM PRODUCT_TBL WHERE ID = :1 AND STATUS != 3");
	stmt->setString(1, "10001");
    ResultSet *rs = stmt->executeQuery();
    while (rs->next())
   {
		string id = rs->getString(1);
		cout << id << endl;
    }
    stmt->closeResultSet(rs);
    conn->terminateStatement(stmt);
	return true;
}
Пример #11
0
void Student::List()
{
  Statement *stmt = NULL;
  ResultSet *rs = NULL;

  string sql = "select * from sql_test_table";

  try
  {
    stmt = conn->createStatement(sql);
  }
  catch (SQLException &e)
  {
    cout << e.getMessage();
  }

  if (stmt)
    {
      try
      {
        rs = stmt->executeQuery();
      }
      catch (SQLException &e)
      {
        cout << e.getMessage();
      }
      if (rs)
        {
          cout << endl << setw(3) << left <<"ID"
                  << setw(6) << left << "NAME"
                     << setw(8) << left << "DEFINITION"
                        << endl;
          cout << "===================" << endl;
          while (rs->next())
            {
              cout << setw(3) << left << rs->getInt(1)
                      << setw(6) << left << rs->getString(2)
                         << setw(8) << left << rs->getString(3)
                            << endl;
            }
          cout << "===================" << endl;
          cout << endl;
          stmt->closeResultSet(rs);
        }
      conn->terminateStatement(stmt);
    }
}
Пример #12
0
vector<Profile> HumanHits::getAllProfilesInSecond(string absoluteTime, string cameraNode)
{
	vector<Profile> profiles;
	driver = sql::mysql::get_mysql_driver_instance();
	con = driver->connect("tcp://127.0.0.1:3306", "root", "root");

	stmt = con->createStatement();
	stmt->execute("USE camera");
	if (cameraNode == "PRG1.avi")
		cameraNode = "camera_node_1";
	else if (cameraNode == "PRG6.avi")
		cameraNode = "camera_node_6";
	else if (cameraNode == "PRG7.avi")
		cameraNode = "camera_node_7";
	else if (cameraNode == "PRG14.avi")
		cameraNode = "camera_node_14";
	else if (cameraNode == "PRG22.avi")
		cameraNode = "camera_node_22";
	else if (cameraNode == "PRG23.avi")
		cameraNode = "camera_node_23";
	else if (cameraNode == "PRG28.avi")
		cameraNode = "camera_node_28";
	else if (cameraNode == "PRG29.avi")
		cameraNode = "camera_node_29";


	string query = "select profile_id, Blob_Center_Point  from " + cameraNode +" where TimeStamp = "+ absoluteTime;
	// select profile_id, timestamp from camera_node_22 where TimeStamp = 1.54;
	ResultSet *profileResult = stmt->executeQuery(query);
	while (profileResult->next())
	{
		Profile prf;
		prf.profileId = profileResult->getString("profile_id");
		string centrePoint = profileResult->getString("Blob_Center_Point");
		vector<string> coord = stringSplit(centrePoint, ",");
		prf.centreX = stoi(coord[0]);
		prf.centreY = stoi(coord[1]);
		profiles.push_back(prf);
	}

	delete con;
	delete stmt;

	return profiles;

}
Пример #13
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);
}}
Пример #14
0
vector<MaintenanceContainer> SqlInterface::getMaintenanceData(){
    ResultSet *rset;
    MaintenanceContainer mContainer;
    int temp2 = 0;
    string query = "select * from maintenance";
    vector<MaintenanceContainer> vContainer;

    if(this == 0 || this == NULL)
        return vContainer;

    stmt = conn->createStatement(query);

    try{
        rset = stmt->executeQuery();
    }
    catch(SQLException ex){
        cout<<"Exception thrown for select"<<endl;
        cout<<"Error number: "<<  ex.getErrorCode() << endl;
        cout<<ex.getMessage() << endl;
    }

    vector<MetaData> data = rset->getColumnListMetaData();

    try{
        while(rset->next()){
            for(unsigned int i = 0; i < data.size(); i++){
                temp = rset->getString(i+1);
                switch(i)
                {
                case 0: temp2 = atoi(temp.c_str());
                    mContainer.setCarId(temp2);
                    break;
                case 1: mContainer.setDamages(temp);
                    break;
                case 2: temp2 = atoi(temp.c_str());
                    mContainer.setCosts(temp2);
                    break;
                case 3: mContainer.setStartDate(temp);
                    break;
                case 4: mContainer.setFinishDate(temp);
                    break;
                }
            }
            vContainer.push_back(mContainer);
        }
    }
    catch(SQLException ex){
        cout<<"Exception thrown for select"<<endl;
        cout<<"Error number: "<<  ex.getErrorCode() << endl;
        cout<<ex.getMessage() << endl;
    }

    stmt->closeResultSet (rset);
    conn->terminateStatement (stmt);

    return vContainer;
}
Пример #15
0
  /**
   * The testing logic of the test case.
   */
  dvoid select ()
  {
    cout << "occipool - Selecting records using ConnectionPool interface" <<
    endl;
    const string poolUserName = "******";
    const string poolPassword = "******";
    const string connectString = "";
    const string username = "******";
    const string passWord = "******";
    unsigned int maxConn = 5;
    unsigned int minConn = 3;
    unsigned int incrConn = 2;
    ConnectionPool *connPool;
    try{
    connPool = env->createConnectionPool
      (poolUserName, poolPassword, connectString, minConn, maxConn, incrConn);
    if (connPool)
      cout << "SUCCESS - createConnectionPool" << endl;
    else
      cout << "FAILURE - createConnectionPool" << endl;
    con = connPool->createConnection (username, passWord);
    if (con)
      cout << "SUCCESS - createConnection" << endl;
    else
      cout << "FAILURE - createConnection" << endl;
    }catch(SQLException ex)
    {
     cout<<"Exception thrown for createConnectionPool"<<endl;
     cout<<"Error number: "<<  ex.getErrorCode() << endl;
     cout<<ex.getMessage() << endl;
     return;
    }

    cout << "retrieving the data" << endl;

    try{
      stmt = con->createStatement 
        ("SELECT author_id, author_name FROM author_tab");
      ResultSet *rset = stmt->executeQuery();
      while (rset->next())
      {
        cout << "author_id:" << rset->getInt (1) << endl;
        cout << "author_name:" << rset->getString (2) << endl;
      }
      stmt->closeResultSet (rset);
      con->terminateStatement (stmt);
      connPool->terminateConnection (con);
      env->terminateConnectionPool (connPool);
    }catch(SQLException ex)
    {
      cout<<"Exception thrown for retrieving data"<<endl;
      cout<<"Error number: "<<  ex.getErrorCode() << endl;
      cout<<ex.getMessage() << endl;
    }

    cout << "occipool - done" << endl;
  } // end of test (Connection *)
Пример #16
0
int Call::DBread(Connection *sqlCon)
{
	if (!sqlCon || !id)
		return -1;
	PreparedStatement *pstmt = sqlCon->prepareStatement(
			"SELECT phone, client, translator, client_country, translator_country, lang, price, start_time, accounted, cost, error FROM calls WHERE id=(?)");
	pstmt->setInt(1, id);

	ResultSet *res;
	try {
		res = pstmt->executeQuery();
	} catch (SQLException &ex) {
		log(LOG_ERROR, "[%s] MySQL error(%d): %s", __func__, ex.getErrorCode(), ex.what());
		delete pstmt;
		return 0;
	}
	delete pstmt;
	if (res->rowsCount() != 1)
		return -1;
	res->first();
	bool isPhone = dynamic_cast<PhoneCall *>(this) != 0;
	if (res->getInt("phone") != isPhone) {
		delete res;
		return -1;
	}
	client = res->getInt("client");
	translator = res->getInt("translator");
	translateLang = res->getString("lang").c_str();
	price = res->getInt("price");
	const char *time = res->getString("start_time").c_str();
	if (strlen(time) > 0)
		start_time = mktime(getdate(time));
	time = res->getString("end_time").c_str();
	if (strlen(time) > 0)
		end_time = mktime(getdate(time));
	accounted = res->getInt("accounted");
	cost = res->getInt("cost");
	if (res->getInt("error"))
		state = ERROR;
//	setClientCountry(res->getString("client_country").c_str());
//	setTranslatorCountry(res->getString("translator_country").c_str());
	delete res;
	return 0;
}
Пример #17
0
bool XMLProcessor::getExistingHashtoDBNameInfo()
{
	vector<pair<string, string>> vec;
	try
	{
		ResultSet* resultset = dbConnect.querybyExistingColumnName(HASHNAMETOTRUETABLENAME, vec);
		countSameNode.clear();
		while (resultset->next())
		{
			nodeToDBName[resultset->getString(HASHNAME)] = resultset->getString(TRUETABLENAME) + "_" + resultset->getString(NAMEINDEX);
			countSameNode[resultset->getString(TRUETABLENAME)]++;
		}
	}
	catch (exception e)
	{
		return false;
	}
	return true;
}
Пример #18
0
std::list<Classroom> find(std::string condition)
{
    ResultSet *res;
    std::list<Classroom> classroom_list;

    std::string sql = "SELECT * FROM classroom WHERE "
                      + condition;
    DButil *myDB;
    res = myDB->execQuery(sql);
    while(res->next())
    {
        Classroom *classroom = new Classroom();
        classroom->set_classroom_id(res->getInt("classroom_id"));
        classroom->set_classroom_name(res->getString("classroom_name"));
        classroom->set_classroom_way(res->getString("classroom_way"));

        classroom_list.push_back(*classroom);
    }
    return classroom_list;
}
Пример #19
0
vector<Profile> HumanHits::getAllProfilesInSecond(string absoluteTime, string cameraNode)
{
    vector<Profile> profiles;
    stmt->execute("USE camera");
    if (cameraNode == "PRG1.avi")
        cameraNode = "camera_node_1";
    else if (cameraNode == "PRG6.avi")
        cameraNode = "camera_node_6";
    else if (cameraNode == "PRG7.avi")
        cameraNode = "camera_node_7";
    else if (cameraNode == "PRG14.avi")
        cameraNode = "camera_node_14";
    else if (cameraNode == "PRG22.avi")
        cameraNode = "camera_node_22";
    else if (cameraNode == "PRG23.avi")
        cameraNode = "camera_node_23";
    else if (cameraNode == "PRG28.avi")
        cameraNode = "camera_node_28";
    else if (cameraNode == "PRG29.avi")
        cameraNode = "camera_node_29";


    string query = "select profile_id, Blob_Center_Point  from " + cameraNode +" where TimeStamp = "+ absoluteTime +" AND  Blob_Center_Point NOT LIKE 'MISSING'";
    // select profile_id, timestamp from camera_node_22 where TimeStamp = 1.54;
    ResultSet *profileResult = stmt->executeQuery(query);
    while (profileResult->next())
    {
        Profile prf;
        prf.profileId = profileResult->getString("profile_id");
        string centrePoint = profileResult->getString("Blob_Center_Point");
        vector<string> coord = stringSplit(centrePoint, ",");
        prf.centreX = stoi(coord[0]);
        prf.centreY = stoi(coord[1]);
        profiles.push_back(prf);
    }



    return profiles;

}
Пример #20
0
 vector<map<string, string>> retrievePendingMessages(Document & request)
 {
     int recvid= validateToken(request["usertoken"].GetString());
     try
     {
         PreparedStatement * prepstmt;
         prepstmt = conn->prepareStatement("select senderuid, receiveruid, msg, datesent from msgs where (receiveruid=? and status=0);");
         prepstmt->setInt(1, recvid);
         ResultSet * rs;
         rs = prepstmt->executeQuery();
         prepstmt = conn->prepareStatement("update msgs set status=1 where receiveruid=?;"); //ATTENTION! Threading error can occur!
         prepstmt->setInt(1, recvid);
         prepstmt->executeUpdate();
         conn->commit();
         ResultSet * namers;
         prepstmt = conn->prepareStatement("select login from users where id=?;");
         prepstmt->setInt(1, recvid);
         namers = prepstmt->executeQuery();
         namers->next();
         string receiver = namers->getString("login");
         vector<map<string, string>> msgs;
         while(rs->next()){
             map<string, string> onemsg;
             prepstmt = conn->prepareStatement("select login from users where id=?;");
             prepstmt->setInt(1, rs->getInt("senderuid"));
             namers = prepstmt->executeQuery();
             namers->next();
             onemsg.insert(make_pair("sender", namers->getString("login")));
             onemsg.insert(make_pair("receiver", receiver));
             onemsg.insert(make_pair("message", rs->getString("msg")));
             onemsg.insert(make_pair("datesent", rs->getString("datesent")));
             //cout << namers->getString("login") << "    " << rs->getString("msg") << endl;
             msgs.push_back(onemsg);
         }
         return msgs;
     }
     catch(exception e)
     {
         throw 2;
     }
 }
Пример #21
0
void Database::establishServer()
{
    if (!isConnected())
        init();

    if (!m_isConnected)
        return;

    if(m_isConnected)
    {
        PreparedStatement *prep_stmt = 0;
        Statement *stmt= 0;
        ResultSet *res = 0;
        QString IP;

        stmt = m_database->createStatement();

        try
        {
            QString qry = QString("SELECT USER( ) AS a");

            res = stmt->executeQuery(qry.toStdString());

            if (res -> rowsCount() != 0)
            {
                while (res->next())
                {
                    IP =  QString(res->getString("a").c_str());
                }
            }

            m_serverID = Crypto::sessionId(IP).toHex();
            prep_stmt = m_database->prepareStatement("INSERT INTO servers(id, serverName, maxPlayers, connectedPlayers, ipAddr) VALUES (?, ?, ?, ?, ?)");

            prep_stmt->setString(1, m_serverID.toStdString());
            prep_stmt->setString(2, m_settings.value("serverName", DefaultSettings::serverName()).toString().toStdString());
            prep_stmt->setInt(3, m_settings.value("maxPlayers", DefaultSettings::maxPlayers()).toInt());
            prep_stmt->setInt(4, 0);
            prep_stmt->setString(5, m_settings.value("serverIP", "127.0.0.1").toString().toStdString());

            prep_stmt->executeUpdate();
        }
        catch (SQLException &e)
        {
            emit writeToConsole("Query failed(establishServer): " + QLatin1String(e.getSQLStateCStr()));
        }

        delete prep_stmt;
        delete stmt;
        delete res;
    }
}
Пример #22
0
std::auto_ptr<std::map<std::string , model::ConfigItem>> ConfigConnector::getConfigInfo()
{
	Connection conn = _pool->getConnection();

	PreparedStatement stmt = conn->prepareStatement("select * from config_resource");
	 

	 ResultSet result = stmt->executeQuery();
	 std::auto_ptr<std::map<std::string ,model::ConfigItem >> mapConfig(new std::map<std::string , model::ConfigItem>);
	 model::ConfigItem item;
	 while (result->next()) {
		 
		 item.setCid(result->getInt(1));
		 item.setName(result->getString(2));
		 item.setValue(result->getString(3));
		 item.setDetail(result->getString(4));

		(*mapConfig)[item.getName()] = item;
	 }

	_pool->returnConnection(conn);

	return mapConfig;
}
Пример #23
0
void display::DisplayLocations()
{
    string query = "select * from LocationInfo";
    ResultSet* res = BaseDBTable::ExecuteQuery(query);
    int index = 1;
    if(res != NULL)
    {
        int rowCount = res->rowsCount();
        if(rowCount != 0 && res->next())
        {
            cout<< index <<": "<< res->getString("Location")<<endl;
            index++;
        }
    }
}
Пример #24
0
void display::DisplayShelves(int locationID)
{
    string query = "select * from ShelfInfo where ShelfLocationID = ";
    query.append(to_string(locationID));
    ResultSet* res = BaseDBTable::ExecuteQuery(query);
    int index = 1;
    if(res != NULL)
    {
        int rowCount = res->rowsCount();
        if(rowCount != 0 && res->next())
        {
            cout<< index <<": "<< res->getString("ShelfCode")<<endl;
            index++;
        }
    }
}
Пример #25
0
void LoginCheck::check(Buf* pbuf) {
    struct sLogin login;

    memcpy(&login, ((MSG_HEAD*)pbuf->ptr())->cData(), sizeof(login));

    PreparedStatement* pstmt = DATABASE->preStatement(SQL_SELECT_STU);
    pstmt->setString(1, login.username);
    ResultSet* prst = pstmt->executeQuery();
    string strpwd;
    while(prst->next()) {
        strpwd = prst->getString(1);
    }

    if (0 == strcmp(login.password, strpwd.c_str())) {
        printf("login success!\n");
    }
}
Пример #26
0
void CHandleMessage::handleGetStoreBooksList (Buf *p) {
#ifdef __DEBUG_HANDLE_HEAD_
	cout << "CT_GetStoreBooksList" << endl;
#endif	
        const epUser* pUser = EPMANAGER->getUserByFd(p->getfd());
        CHECK_P(pUser);

        cGetPublicBooksList cgbl;
        UNPACKET(p, cgbl);

        bookList book_list;
        bookNode* book_node;
        try {
                MutexLockGuard guard(DATABASE->m_mutex);
                PreparedStatement* pstmt = DATABASE->preStatement(SQL_GET_COURSE_LIST_IN_STORE);
                ResultSet* prst = pstmt->executeQuery ();
                while (prst->next ()) {
                        book_node = book_list.add_book_list();
                        book_node->set_book_id  (prst->getInt   ("book_id"));
                        book_node->set_book_name(prst->getString("book_name"));
                        book_node->set_book_type(prst->getInt   ("book_type"));
                        book_node->set_auth_id  (prst->getInt   ("auth_id"));
                        book_node->set_auth_type((enum LoginType)prst->getInt   ("auth_type"));
#ifdef __DEBUG__
                        std::cout << "book_node->book_id  () = " << book_node->book_id  () << std::endl;
                        std::cout << "book_node->book_name() = " << book_node->book_name() << std::endl;
                        std::cout << "book_node->book_type() = " << book_node->book_type() << std::endl;
                        std::cout << "book_node->auth_id  () = " << book_node->auth_id  () << std::endl;
                        std::cout << "book_node->auth_type() = " << book_node->auth_type() << std::endl;
#endif
                }
                delete prst;
                delete pstmt;
        }catch (SQLException e) {
                PRINT_CATCH(e);
                RETURN(p);
        }

        Buf* pBuf = packet_list(ST_GetStoreBooksList, book_list, p->getfd());
        CHECK_P(pBuf);
        SINGLE->sendqueue.enqueue(pBuf);

        RETURN(p);
}
Пример #27
0
Player *Database::authenticateUser(const QString &user, const QString &password)
{
    if (!isConnected())
        init();

    if (!m_isConnected)
        return 0;

    Player *player = 0;

    Statement *stmt = 0;
    ResultSet *res = 0;

    stmt = m_database->createStatement();

    try {
        QString qry = QString("SELECT id, username, kills, deaths FROM accounts where username='******' and secret='%2'").arg(user, password);

        res = stmt->executeQuery(qry.toStdString());

        if (res -> rowsCount() != 0)
        {
            player = new Player();

            while (res->next())
            {
                player->setUserId(res->getInt("id"));
                player->setUserName(QString::fromStdString(res->getString("username")));
                player->setKills(res->getInt("kills"));
                player->setDeaths(res->getInt("deaths"));
            }
        }
    } catch (SQLException &e)
    {
        emit writeToConsole("Query failed: " + QLatin1String(e.getSQLStateCStr()));
        return false;
    }

    delete stmt;
    delete res;

    return player;
}
Пример #28
0
 vector<string> getUserMatches(Document & request){
     validateToken(request["usertoken"].GetString());
     try{
         PreparedStatement * prepstmt;
         prepstmt = conn -> prepareStatement("select login from users where login like ?;");
         string tomatch = request["data"][0].GetString();
         tomatch += "%"; //Search not only for the matchreq, but for all the str beginning with it
         prepstmt -> setString(1, tomatch);
         ResultSet * rs;
         rs = prepstmt -> executeQuery();
         vector<string> strmatch;
         while(rs->next()){
             strmatch.push_back(rs->getString("login"));
         }
         return strmatch;
     }
     catch(exception e){
         throw 2;
     }
 }
Пример #29
0
  /**
   * displaying all the rows in the table
   */
  void displayAllRows ()
  {
    string sqlStmt = "SELECT author_id, author_name FROM author_tab \
    order by author_id";
    stmt = conn->createStatement (sqlStmt);
    ResultSet *rset = stmt->executeQuery ();
    try{
    while (rset->next ())
    {
      cout << "author_id: " << rset->getInt (1) << "  author_name: " 
        << rset->getString (2) << endl;
    }
    }catch(SQLException ex)
    {
     cout<<"Exception thrown for displayAllRows"<<endl;
     cout<<"Error number: "<<  ex.getErrorCode() << endl;
     cout<<ex.getMessage() << endl;
    }

    stmt->closeResultSet (rset);
    conn->terminateStatement (stmt);
  }
void SimpleDataSet::read(int type){  
    openMysqlSession();
    
    this->dataSet.clear();
    
    ResultSet *resSet;
    PreparedStatement *prep_stmt;

    /* create a statement object */
    prep_stmt = con -> prepareStatement("SELECT * FROM `SimpleDataSet` WHERE `compression_rate`=? AND `num_clusters`=? AND `type`=?");
    prep_stmt->setInt(1, compressionRate);  
    prep_stmt->setInt(2, numClusters);      
    prep_stmt->setInt(3, type);      
    resSet = prep_stmt->executeQuery();

    while (resSet->next()) {       
        std::stringstream datastream(resSet->getString("sequence"));        
        //for each loop we save one sequence
        vector<int> sequence;
        while (!datastream.eof()) {
            int state;
            datastream >> state;
            sequence.push_back(state);
        }        
        SimpleData newSD;
        newSD.sequence=sequence;
        newSD.idAction=resSet->getInt("id_action");
        this->dataSet.push_back(newSD);
    }
    
    delete resSet;
    delete prep_stmt;
    
    closeMysqlSession();
    
    cout<<"SimpleData readad: "<<this->dataSet.size()<<" data, each sequence length:"<<this->dataSet[0].sequence.size()<<endl;
    
}