Enzo
Enzo

Reputation: 962

Only one connection to database and use functions, C++

I have a class to connect MySQL database. This class has 4 methods. (insert, getResults etc.) I don't want to create database connection in every method. So i want an init() when we create this object. Is connection pool solution of my problem? How can i solve?

Have 4 methods like that:

bool DataAccessObject::getResults(short int data, std::vector<FaceRecord>* rec)
{
//    DataAccessObject *temp = new DataAccessObject();

    bool ret = false;

    try{
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;
        sql::PreparedStatement *prepStmt;

        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "root");

        /* Connect to the MySQL test database */
        con->setSchema("test");

        std::stringstream s;
        s << "SELECT * FROM Amts WHERE "<< data <<" = "<< data <<"";

        prepStmt = con->prepareStatement (s.str());
        res = prepStmt->executeQuery();

        while(res->next()){
            tempFR.uuId = res->getInt64("uuId");
            tempFR.cameraNo = res->getInt("cameraNo");
            tempFR.age = res->getInt("age");
            tempFR.gender = res->getInt("gender");
            tempFR.time = res->getString("time");
            tempFR.image = res->getString("image");
            rec->push_back(tempFR);
        }


        //return true;
        ret = true;
    }

    catch (sql::SQLException &e)
    {

        std::cout << "# ERR: SQLException in " << __FILE__;
        std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl;
        std::cout << "# ERR: " << e.what();
        std::cout << " (MySQL error code: " << e.getErrorCode();
        std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;

    }

    return ret;

}

Upvotes: 1

Views: 532

Answers (1)

Dannie
Dannie

Reputation: 2480

You can use the C++ Singleton design pattern so that your init is called only once when you create it.

Upvotes: 1

Related Questions