Пример #1
0
/**
 * Find the latest statistic
 */
Stat* StatController::GetLatestStat()
{
	PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM stats ORDER BY id DESC LIMIT 1");

	ResultSet* rs = stmt->executeQuery();

	delete stmt;

	if(rs != NULL)
	{
		while(rs->next())
		{
			//Return the latest statistic (by id)
			Stat* s = GenerateStat(*rs);
			delete rs;
			return s;
		}
	}
	else
	{
		return NULL;
	}

	return NULL;
}
Пример #2
0
unsigned int CallManager::storeCall(Connection *sqlCon, bool phone, unsigned int client, unsigned int translator)
{
	if (!sqlCon)
		return 0;
	PreparedStatement *pstmt = sqlCon->prepareStatement(
			"INSERT INTO calls SET phone=(?), client=(?), translator=(?), request_time=NOW()");
	pstmt->setInt(1, phone);
	pstmt->setInt(2, client);
	pstmt->setInt(3, translator);

	try {
		pstmt->execute();
	} catch (SQLException &ex) {
		log(LOG_ERROR, "[%s] MySQL error(%d): %s", __func__, ex.getErrorCode(), ex.what());
		delete pstmt;
		return 0;
	}
	delete pstmt;

	pstmt = sqlCon->prepareStatement("SELECT LAST_INSERT_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;
	res->first();
	unsigned int id = res->getInt(1);
	delete res;
	return id;
}
/**
 * Find all content placeholders that belong to the sheet of that id
 */
vector<ContentPlaceholder*> ContentPlaceholderController::GetContentPlaceholdersBySheetId(int sheetId)
{
	PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM cph WHERE sheetid = ?");
	
	stmt->setInt(1, sheetId);

	ResultSet* rs = stmt->executeQuery();

	delete stmt;

	vector<ContentPlaceholder*> cphs;
	if(rs != NULL)
	{
		while(rs->next())
		{
			//For all content placeholders matching the query, add them to the vector
			cphs.push_back(GenerateContentPlaceholder(*rs));
		}

		delete rs;
	}

	return cphs;

}
Пример #4
0
/**
 * Find the stat with that id
 */
Stat* StatController::GetStatById(int id)
{
	PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM stats WHERE id = ?");
	
	stmt->setInt(1, id);

	ResultSet* rs = stmt->executeQuery();

	delete stmt;

	if(rs != NULL)
	{
		while(rs->next())
		{
			//If a stat matches this id, return it
			Stat* s = GenerateStat(*rs);
			delete rs;
			return s;
		}
	}
	else
	{
		return NULL;
	}

	return NULL;
}
/**
 * Find the content placeholder with that id
 */
ContentPlaceholder* ContentPlaceholderController::GetContentPlaceholderById(int id)
{
	PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM cph WHERE id = ?");
	
	stmt->setInt(1, id);

	ResultSet* rs = stmt->executeQuery();

	delete stmt;

	if(rs != NULL)
	{
		while(rs->next())
		{
			//Return the content placeholder retrieved by the query
			ContentPlaceholder* c = GenerateContentPlaceholder(*rs);
			delete rs;
			return c;
		}
	}
	else
	{
		return NULL;
	}

	return NULL;
}
Пример #6
0
void Database::updatePlayer(Player *player)
{
    if (!isConnected())
        init();

    if (!m_isConnected)
        return;

    PreparedStatement *statement = 0;

    try
    {
        statement = m_database->prepareStatement("UPDATE accounts SET kills = ?, deaths = ? WHERE id = ?");
        statement->setInt(1, player->kills());
        statement->setInt(2, player->deaths());
        statement->setInt(3, player->userId());

        statement->executeQuery();
    }
    catch (SQLException &e)
    {
        emit writeToConsole("Query failed(updatePlayer): " + QLatin1String(e.getSQLStateCStr()));
    }

    delete statement;
}
Пример #7
0
void Database::updatePlayerCount(int count)
{
    if (!isConnected())
        init();

    if (!m_isConnected)
        return;

    PreparedStatement *statement = 0;

    try
    {
        statement = m_database->prepareStatement("UPDATE servers SET connectedPlayers = ? WHERE id = ?");
        statement->setInt(1, count);
        statement->setString(2, m_serverID.toStdString());

        statement->executeQuery();
    }
    catch (SQLException &e)
    {
        emit writeToConsole("Query failed(updatePlayerCount): " + QLatin1String(e.getSQLStateCStr()));
    }

    delete statement;
}
Пример #8
0
    void authorize(Document & request)
    {
        if(request["data"].Size() > 0)
        {
            if(request["data"][0].HasMember("login") && request["data"][0].HasMember("password"))
            {
                try
                {
                    PreparedStatement * prepstmt;
                    prepstmt = conn->prepareStatement("select ((select pwdhash from users where login=?) = (sha1(?) collate utf8_general_ci) is true) as val;");
                    prepstmt->setString(1, request["data"][0]["login"].GetString());
                    prepstmt->setString(2, request["data"][0]["password"].GetString());
                    ResultSet * rs;
                    rs = prepstmt->executeQuery();
                    rs->next();
                    if(rs->getBoolean("val")) return;
                    throw 4;
                }
                catch(SQLException e)
                {
                    throw 2;
                }

            }
        }
        else throw 0;
    }
Пример #9
0
/**
 * Find the layout with that id
 */
Layout LayoutController::GetLayoutById(int id)
{
	PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM layouts WHERE id = ?");
	
	stmt->setInt(1, id);

	ResultSet* rs = stmt->executeQuery();
	delete stmt;
	
	if(rs != NULL)
	{
		while(rs->next())
		{
			//If a layout matches that id, return it
			return GenerateLayout(*rs);
		}
	}
	else
	{
		Layout l;
		return l;
	}

	Layout l;
	return l;
}
Пример #10
0
int main()
{
	try
	{
		clock_t tStart = clock();

		readConfFile();
		cout<<"Started the program\n";
		//cout<<tabIndex;

		DBConnection *squidLog = new DBConnection();
		squidLog->dbConnOpen("127.0.0.1","3306","root","simple","squid");

		string logReadQuery = "select * from access_log_new where id > ?;";
		PreparedStatement *pstm = squidLog->conn->prepareStatement(logReadQuery);
		pstm->setInt(1,tabIndex);
		squidLog->res = pstm->executeQuery();


	/*DBConnection *squidLog = new DBConnection();
	squidLog->dbConnOpen("127.0.0.1","3306","root","simple","squid");

	squidLog->tableName = "access_log";
	squidLog->setReadPstmt(1,squidLog->tableName,"","");
	squidLog->readTable();*/


		statLog = new DBConnection();
		createStatistics(squidLog,statLog);


	/*grossStatisticsAcc(statLog->tableNameAcc);
	grossStatisticsDen(statLog->tableNameDen);
	createDomainStatisticsAcc(statLog->tableNameAcc);
	createUserStatisticsAcc(statLog->tableNameAcc);
	createDomainStatisticsDen(statLog->tableNameDen);
	createUserStatisticsDen(statLog->tableNameDen);*/

		writeConfFile();
		printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
		cout<<"End Of program \n";

	}
	catch (sql::SQLException &e)
	{
		cout << "# ERR: SQLException in " << __FILE__;
		cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
		cout << "# ERR: " << e.what();
		cout << " (MySQL error code: " << e.getErrorCode();
		cout << ", SQLState: " << e.getSQLState() << " )" << endl;
	}
	catch (exception& e)
	{
		cout << "# ERR File: " << __FILE__;
		cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
	    cout << e.what() << '\n';
	}
		return 0;
}
Пример #11
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;
     }
 }
Пример #12
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");
    }
}
Пример #13
0
int PhoneCall::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, request_time, confirm_time, accepted 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();
	if (!res->getInt("phone")) {
		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));
	accounted = res->getInt("accounted");
	cost = res->getInt("cost");
	if (res->getInt("error"))
		state = ERROR;
	time = res->getString("request_time").c_str();
	if (strlen(time) > 0)
		request_time = mktime(getdate(time));
	time = res->getString("confirm_time").c_str();
	if (strlen(time) > 0)
		confirm_time = mktime(getdate(time));
	accepted = res->getBoolean("accepted");
	setClientCountry(res->getString("client_country").c_str());
	setTranslatorCountry(res->getString("translator_country").c_str());
	delete res;
	return 0;
}
Пример #14
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);
}
Пример #15
0
 int validateToken(string token)
 {
     PreparedStatement * prepstmt;
     prepstmt = conn -> prepareStatement("select ((select expiry from tokens where token=?) > now() is true) as res, (select userid from tokens where token=?) as userid;");
     prepstmt->setString(1, token);
     prepstmt->setString(2, token);
     try
     {
         ResultSet * rs;
         rs = prepstmt->executeQuery();
         rs->next();
         if(rs->getBoolean("res")) return rs->getInt("userid");
         throw 3;
     }
     catch(exception e)
     {
         throw 2;
     }
 }
Пример #16
0
 bool validateTokenByName(string user, string token)
 {
     PreparedStatement * prepstmt;
     prepstmt = conn -> prepareStatement("select ((select expiry from tokens where (userid=(select id from users where login=?) and token=?)) > now() is true) as res;");
     prepstmt->setString(1, user);
     prepstmt->setString(2, token);
     try
     {
         ResultSet * rs;
         rs = prepstmt->executeQuery();
         string a = rs->getMetaData()->getColumnLabel(1);
         rs->next();
         if(rs->getBoolean(a))return true;
         throw 3;
     }
     catch(exception e)
     {
         throw 2;
     }
 }
Пример #17
0
					Collection *JDBCTemplate::getByCondition(std::string sql, object *qm)
					{
						Collection *col = std::vector();
						Connection *conn = 0;
						try
						{
							//调用钩子方法
							conn = this->getConnection();
							//调用原语操作
							sql = this->prepareQuerySql(sql, qm);
							PreparedStatement *pstmt = conn->prepareStatement(sql);
							//调用原语操作
							this->setQuerySqlValue(pstmt, qm);
							ResultSet *rs = pstmt->executeQuery();
							while(rs->next())
							{
								//调用原语操作
								col->add(this->rs2Object(rs));
							}
							rs->close();
							pstmt->close();
						}
						catch(Exception *err)
						{
							err->printStackTrace();
						}
//JAVA TO C++ CONVERTER TODO TASK: There is no native C++ equivalent to the exception 'finally' clause:
						finally
						{
							try
							{
								conn->close();
							}
							catch (SQLException *e)
							{
								e->printStackTrace();
							}
						}
						return col;
					}
Пример #18
0
/**
 * Find all sheets that belong to that user
 */
vector<Sheet*> SheetController::GetSheetsByUsername(string username)
{
	PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM sheets WHERE username = ?");
	
	stmt->setString(1, username);

	ResultSet* rs = stmt->executeQuery();

	vector<Sheet*> sheets;
	if(rs != NULL)
	{
		while(rs->next())
		{
			//Add matching sheets to a vector
			sheets.push_back(GenerateSheet(*rs));
		}
	}

	delete stmt;
	delete rs;

	return sheets;

}
Пример #19
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;
}
Пример #20
0
/*
=====================
 获得数据库表纪录
=====================
*/
bool CHandleMessage::postDBRecord (Buf* buf, int iCase)
{
#if 0
    if (NULL == buf) {
        printf("null buf\n");
        return false;
    }

    MSG_HEAD head;

    try {
        MutexLockGuard guard(DATABASE->m_mutex);
        PreparedStatement* pstmt = NULL;

        if (iCase == 1)
            pstmt = DATABASE->preStatement (SQL_SELECT_COURSE_DB);
        else if (iCase == 2)
            pstmt = DATABASE->preStatement (SQL_SELECT_GRADE_DB);
        else if (iCase == 3)
            pstmt = DATABASE->preStatement (SQL_SELECT_CLASS_DB);
        else if (iCase == 4)
            pstmt = DATABASE->preStatement (SQL_SELECT_CLASSROOM_DB);
        else if (iCase == 5)
            pstmt = DATABASE->preStatement (SQL_SELECT_STUDENT_DB);
        else if (iCase == 6) {
            pstmt = DATABASE->preStatement (SQL_SELECT_COURSEITEM_DB);
#if 1   // send count of all selected course by teacher
            #ifdef _TEACHER_NOLOGIN
            // only for h**king test............
            pstmt->setString (1, "拼图");
            pstmt->setString (2, "造房子");
            pstmt->setString (3, "暖身操");
            pstmt->setString (4, "动画片");
            #else
            CRoom* room = ROOMMANAGER->get_room_by_fd (buf->getfd());
            if (room != NULL)
            {
                CRoom::COURSELIST::iterator it;
                int ii = 1;
                for (it = room->m_course_list.begin (); it != room->m_course_list.end (); ++it)
                    pstmt->setString (ii++, (*it)->getName());
            }
            #endif
#else
            sGetCourseItem* ci = (sGetCourseItem *) ((char*)((MSG_HEAD*)buf->ptr()) + sizeof (MSG_HEAD));
            pstmt->setString (1, ci->sCourseName);
#endif
        }
        else {
            cout << "error: index" << endl;
            return false;
        }

        ResultSet* prst = pstmt->executeQuery();
        unsigned int index = 0, type = 0;
        while(prst->next()) {
            //printf ("index = %d------------------------------------------------------\n", index);
            if (iCase == 1) {
                memset (&head, 0x00, sizeof (head));
                //head.cType = CT_GetCourseDB * 100 + index++;
                type = 5000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                head.cLen = sizeof(MSG_HEAD) + sizeof(struct sGetCourseDB);
                struct sGetCourseDB course_info;
                (void) memset (&course_info, 0x00, sizeof (sGetCourseDB));

                strcpy(course_info.sGradeName, prst->getString ("grade_name").c_str());
                strcpy(course_info.sGroupName, prst->getString ("group_name").c_str());
                strcpy(course_info.sCourseName, prst->getString("course_name").c_str());

                course_info.iLanguage   = prst->getInt ("language");
                course_info.iArt        = prst->getInt ("art");
                course_info.iCommunity  = prst->getInt ("community");
                course_info.iHealth     = prst->getInt ("health");
                course_info.iScience    = prst->getInt ("science");

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy(p->ptr(), &head, sizeof(MSG_HEAD));
                memcpy((char*)p->ptr() + sizeof(MSG_HEAD), &course_info, sizeof(struct sGetCourseDB));
                p->setfd(buf->getfd());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue(p);
            }

            else if (iCase == 2) {
                memset (&head, 0x00, sizeof (head));
                type = 3000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                //head.cType = CT_GetGradeDB;
                head.cLen = sizeof (MSG_HEAD)+ sizeof (struct sGetGradeDB);
                struct sGetGradeDB grade_info;
                (void) memset (&grade_info, 0x00, sizeof (grade_info));

                strcpy (grade_info.sGradeName, prst->getString ("grade_name").c_str());

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof(MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof(MSG_HEAD), &grade_info, sizeof(struct sGetGradeDB));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }

            else if (iCase == 3) {
                memset (&head, 0x00, sizeof (head));
                type = 4000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                //head.cType = CT_GetClassDB;
                head.cLen = sizeof(MSG_HEAD)+ sizeof (struct sGetClassDB);
                struct sGetClassDB class_info;
                (void) memset (&class_info, 0x00, sizeof (class_info));

                strcpy (class_info.sClassName, prst->getString ("class_name").c_str());

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof (MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof (MSG_HEAD), &class_info, sizeof (struct sGetClassDB));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }

            else if (iCase == 4) {
                memset (&head, 0x00, sizeof (head));
                //head.cType = CT_GetClassRoomDB;
                type = 6000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                head.cLen = sizeof(MSG_HEAD) + sizeof (struct sGetClassRoomDB);
                struct sGetClassRoomDB room_info;
                (void) memset (&room_info, 0x00, sizeof (room_info));

                strcpy (room_info.sClassRoomName, prst->getString ("classroom_name").c_str());

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof (MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof (MSG_HEAD), &room_info, sizeof (struct sGetClassRoomDB));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }

            else if (iCase == 5) {
                memset (&head, 0x00, sizeof (MSG_HEAD));
                type = 10000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                /// cout << "begin:-head.cType = " << head.cType << endl;
                head.cLen = sizeof (MSG_HEAD) + sizeof (struct sGetAllStudentInfo);
                struct sGetAllStudentInfo stu_info;
                (void) memset (&stu_info, 0x00, sizeof (stu_info));

                strcpy (stu_info.sPicName, prst->getString ("picture_name").c_str());
                strcpy (stu_info.sStudentName, prst->getString ("student_name").c_str());
                stu_info.iStudentId= prst->getInt ("student_id");

                /// cout << "stu_info.iStudentId:" << stu_info.iStudentId << endl;
                /// cout << "stu_info.sPicName:" << stu_info.sPicName << endl;
                /// cout << "stu_info.sStudentName:" << stu_info.sStudentName << endl;

                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof (MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof (MSG_HEAD), &stu_info, sizeof (struct sGetAllStudentInfo));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
                /// cout << "address = " << p << endl;
                /// cout << "ended:-head.cLen = " << head.cLen << endl;
                /// cout << "ended:-head.cType = " << head.cType << endl;
            }

            else if (iCase == 6) {
                memset (&head, 0x00, sizeof (head));
                type = 7000 + index++;
                memcpy (&head.cType, &type, sizeof (unsigned int));
                //head.cType = CT_GetCourseItem;
                head.cLen = sizeof(MSG_HEAD) + sizeof (struct sCourseItem);
                struct sCourseItem course_item;
                (void) memset (&course_item, 0x00, sizeof (sCourseItem));

                strcpy (course_item.sCourseName, prst->getString ("course_name").c_str());
                strcpy (course_item.sItemName, prst->getString ("item_name").c_str());
                strcpy (course_item.sDesc, prst->getString ("fck_desc").c_str());

                cout << "courseName: " << course_item.sCourseName << endl;
                cout << "itemName: " << course_item.sItemName << endl;
                cout << "Desc: " << course_item.sDesc << endl;
                Buf* p = SINGLE->bufpool.malloc ();
                memcpy (p->ptr(), &head, sizeof(MSG_HEAD));
                memcpy ((char *)p->ptr() + sizeof(MSG_HEAD), &course_item, sizeof (struct sCourseItem));
                p->setfd (buf->getfd ());
                p->setsize(head.cLen);
                SINGLE->sendqueue.enqueue (p);
            }
            else {
                cout << "error: index" << endl;
                return false;
            }

        }
#if 1   // send finished flags
        do {
            sleep (1);
            //cout << "send finished flags -----------" << endl;
            Buf* p = SINGLE->bufpool.malloc ();
            MSG_HEAD* phead = (MSG_HEAD*)p->ptr();
            struct sDBRecordFinished finished;
            memset (&finished, 0x00, sizeof (sDBRecordFinished));
            if (iCase == 5)
                finished.iFlagFinished = 10000;
            else
                finished.iFlagFinished = 1;

            phead->cLen = sizeof (MSG_HEAD) + sizeof (struct sDBRecordFinished);
            phead->cType = ST_GetDBRecordFinished;
            memcpy (((char*)p->ptr()) + MSG_HEAD_LEN, &finished, sizeof (struct sDBRecordFinished));
            p->setfd (buf->getfd());
            p->setsize (phead->cLen);
            SINGLE->sendqueue.enqueue (p);
        } while (0);
#endif
    }
    catch(SQLException e){
        LOG(ERROR) << e.what() << std::endl;
    }

    buf->reset();
    SINGLE->bufpool.free(buf);
#endif
    return true;
}
Пример #21
0
/*
=====================
 获得数据库表纪录数量
=====================
*/
bool CHandleMessage::postDBRecordCount (Buf* p, int iCase)
{
#if 0
    char str[1024] = "SELECT count(*) AS ccount FROM ";

    if (NULL == p) {
        printf("null buf\n");
        return false;
    }
    //printf (" postDBRecordCount ..., iCase=%d\n", iCase);
#if 1
    if (iCase == 1) {
        strcat (str, "course_group_course AS cgc, course_group AS cg, course AS c, grade AS g, grade_course AS gc WHERE  cgc.group_id = cg.group_id AND cgc.course_id = c.course_id AND gc.grade_id = g.grade_id AND c.course_id = gc.course_id");
    }
    else if (iCase == 2) {
        strcat (str, "grade");
    }
    else if (iCase == 3) {
        strcat (str, "class");
    }
    else if (iCase == 4) {
        strcat (str, "classroom");
    }
    else if (iCase == 5) {
        strcat (str, "student");
    }
    else if (iCase == 6) {
        //strcat (str, "course_item AS ci, course AS c, item AS i WHERE ci.course_id=c.course_id AND ci.item_id=i.item_id AND c.course_name=?");
        strcat (str, "course_item AS ci, course AS c, item AS i WHERE ci.course_id=c.course_id AND ci.item_id=i.item_id AND (c.course_name=? OR c.course_name=? OR c.course_name=? OR c.course_name=?)");
    }
#endif

    // dbCount.count = 100;
    //
#if 0
    struct sDBCount dbCount;
    dbCount.count = 5;
    MSG_HEAD *head = (MSG_HEAD*) buf->ptr();
    head->cLen = sizeof (MSG_HEAD) + sizeof (dbCount);
    head->cType = CT_GetClassRoomDBCount;
    memcpy (head->cData(), &dbCount, sizeof (dbCount));

    buf->setsize (head->cLen);
    SINGLE->sendqueue.enqueue (buf);
#endif
#if 1

    try {
        MutexLockGuard guard(DATABASE->m_mutex);
        PreparedStatement* pstmt = DATABASE->preStatement(str);
        if (iCase == 6) {
        #if 0 // fixed: to update
            sGetCourseItem* ci = (sGetCourseItem *) ((char*)((MSG_HEAD*)p->ptr()) + sizeof (MSG_HEAD));
            pstmt->setString (1, ci->sCourseName);
        #else
#ifdef _TEACHER_NOLOGIN
            // only for h**king test............
            pstmt->setString (1, "拼图");
            pstmt->setString (2, "造房子");
            pstmt->setString (3, "暖身操");
            pstmt->setString (4, "动画片");
#else
            CRoom* room = ROOMMANAGER->get_room_by_fd (p->getfd());
            if (room != NULL)
            {
                CRoom::COURSELIST::iterator it;
                int ii = 1;
                for (it = room->m_course_list.begin (); it != room->m_course_list.end (); ++it) {
                    pstmt->setString (ii++, (*it)->getName());
                    cout << "COURSE NAME: " << (*it)->getName() << endl;
                }
            }
#endif
        #endif
        }
        ResultSet* prst = pstmt->executeQuery ();
        while (prst->next ()) {
            struct sDBCount dbCount;
            dbCount.count = prst->getInt ("ccount");
            printf ("get db count: %d\n", dbCount.count);
            MSG_HEAD* head = (MSG_HEAD*)p->ptr();
            head->cLen = MSG_HEAD_LEN + sizeof (dbCount);

            if (iCase == 1)
                head->cType = CT_GetCourseDBCount;
            else if (iCase == 2)
                head->cType = CT_GetGradeDBCount;
            else if (iCase == 3)
                head->cType = CT_GetClassDBCount;
            else if (iCase == 4)
                head->cType = CT_GetClassRoomDBCount;
            else if (iCase == 5)
                head->cType = CT_GetAllStudentInfoCount;
            else if (iCase == 6)
                head->cType = CT_GetCourseItemCount;

            //memcpy (head->cData(), &dbCount, sizeof (dbCount));
            memcpy ((char *)p->ptr() + MSG_HEAD_LEN, &dbCount, sizeof (struct sDBCount));

            p->setsize (head->cLen);
            SINGLE->sendqueue.enqueue (p);
        }
        delete pstmt;
        delete prst;
    }
    catch (SQLException e) {
        printf ("%s\n", e.what ());
    }
#endif
#endif
    return true;
}