Only one connection to database and use functions, C++ - 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;
}

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

Related

Cant cout the result that what I want with MySQL and c++

#include <iostream>
#include <Windows.h>
#include "jdbc/mysql_connection.h"
#include "jdbc/cppconn/driver.h"
#include "jdbc/cppconn/exception.h"
#include "jdbc/cppconn/resultset.h"
#include "jdbc/cppconn/statement.h"
#include "jdbc/cppconn/prepared_statement.h"
#ifdef _DEBUG
#pragma comment(lib, "debug/mysqlcppconn.lib")
#else
#pragma comment(lib, "mysqlcppconn.lib")
#endif
using namespace std;
std::string Utf8ToMultiByte(std::string utf8_str);
int main()
{
try
{
sql::Driver* driver;
sql::Connection* connection;
sql::Statement* statement;
sql::ResultSet* resultset;
driver = get_driver_instance();
connection = driver->connect("tcp://127.0.0.1:3306", "root", "");
if (connection == nullptr)
{
cout << "connect failed" << endl;
exit(-1);
}
connection->setSchema("logindata");
statement = connection->createStatement();
resultset = statement->executeQuery("insert into new_table(number, id, wincount, totalgameplay) values(4, 132, 232349, 123)");
resultset = statement->executeQuery("select * from new_table ");
for (;resultset->next();)
{
cout << resultset->getInt("id") << " : " <<
Utf8ToMultiByte(resultset->getString("wincount")) << " : " <<
Utf8ToMultiByte(resultset->getString("totalgameplay")) << endl;
}
delete resultset;
delete statement;
delete connection;
}
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;
}
return 0;
}
std::string Utf8ToMultiByte(std::string utf8_str)
{
std::string resultString; char* pszIn = new char[utf8_str.length() + 1];
strncpy_s(pszIn, utf8_str.length() + 1, utf8_str.c_str(), utf8_str.length());
int nLenOfUni = 0, nLenOfANSI = 0; wchar_t* uni_wchar = NULL;
char* pszOut = NULL;
// 1. utf8 Length
if ((nLenOfUni = MultiByteToWideChar(CP_UTF8, 0, pszIn, (int)strlen(pszIn), NULL, 0)) <= 0)
return nullptr;
uni_wchar = new wchar_t[nLenOfUni + 1];
memset(uni_wchar, 0x00, sizeof(wchar_t)*(nLenOfUni + 1));
// 2. utf8 --> unicode
nLenOfUni = MultiByteToWideChar(CP_UTF8, 0, pszIn, (int)strlen(pszIn), uni_wchar, nLenOfUni);
// 3. ANSI(multibyte) Length
if ((nLenOfANSI = WideCharToMultiByte(CP_ACP, 0, uni_wchar, nLenOfUni, NULL, 0, NULL, NULL)) <= 0)
{
delete[] uni_wchar; return 0;
}
pszOut = new char[nLenOfANSI + 1];
memset(pszOut, 0x00, sizeof(char)*(nLenOfANSI + 1));
// 4. unicode --> ANSI(multibyte)
nLenOfANSI = WideCharToMultiByte(CP_ACP, 0, uni_wchar, nLenOfUni, pszOut, nLenOfANSI, NULL, NULL);
pszOut[nLenOfANSI] = 0;
resultString = pszOut;
delete[] uni_wchar;
delete[] pszOut;
return resultString;
}
why I cant get result of table information?
does insert and select then cout is not proper process?
Also I try with PrepareStatement with above the select phrase. But I worked properly
I know that preparestatement and createstatement is different with dynamic parsing and static parsing. what is more efficient with adding information to database?

Connect to an online db in c++

I created my database in phpMyAdmin from godaddy.com.
But i can't seem to find a way to connect to it.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
#pragma comment(lib, "mysqlcppconn.lib")
const string server = "myWebsite";
const string username = "username";
const string password = "password";
int main()
{
sql::Driver *driver;
sql::Connection *dbConn;
sql::Statement *stmt;
sql::ResultSet *res;
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
try
{
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
stmt = dbConn->createStatement();
try
{
stmt->execute("USE test");
res = stmt->executeQuery("SELECT * FROM users");
}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
sql::ResultSetMetaData *res_meta = res -> getMetaData();
int columns = res_meta -> getColumnCount();
while (res->next())
{
for (int i = 1; i <= columns; i++) {
cout << res->getString(i) << " | " ;
}
cout << endl;
}
delete res;
delete stmt;
delete dbConn;
return 0;
}
But i get this error:
Could not connect to database. Error message: Access denied for user 'username'#'IP' (using password: YES)
This code works fine with the local phpmyadmin databases.
So is there any different way to connect to databases that are hosted on a website?

Creating temporary table while still accessing other tables

I've got 2 or more databases ATTACHed to one SQLite database connection. Each database consists of 3 tables. To have better access for searching/filtering, I create a huge temporary table over all tables and databases like this:
"CREATE TEMPORARY TABLE temp_table AS "
"SELECT * FROM pb.name_table "
"LEFT JOIN pb.phone_table ON (pb.name_table.id=pb.phone_table.id) " \
"LEFT JOIN pb.email_table ON (pb.name_table.id=pb.email_table.id) " \
"UNION SELECT * FROM name_table " \<br>
"LEFT JOIN phone_table ON (name_table.id=phone_table.id) " \
"LEFT JOIN email_table ON (name_table.id=email_table.id);";
If something changes in a table, I have to recreate the temporary table. With an increasing amount of data, creating a temporary table takes some time, but since I'm having continuous read access to the table, my idea was as follows:
Create a thread, which creates a second temp table in background
Block access for the reading clients
DROP first temp table
Rename the second temp table
The problem is now: Creating a temporary table is a write access to the database, which blocks automatically all reading threads also.
Has anyone a good idea how I can handle this? I need read access while recreating the temporary table.
As long as all threads are part of the same program, you have control over all database connections.
So you can write the data in a completely separate database, and ATTACH is quickly later.
Thanks a lot for your answer. I changed my code and found out that I need a new database connection (sqlite3_open) in the working thread not to block the other thread. Also creating a TEMPORARY TABLE in the attached "temporary database" was not possible, because creating a temporary table doesn't allow a qualifier (like: x.temp_table), so I had to create a real table which consumes a lot of memory in our flash file system (which is not allowed).
But wait! I've got an idea
(2 hours later)
I did it! I open an empty database and attach alll relevant databases to the connection. I create a temporary table "in" the empty database which consumes no memory in flash, because it's temporary.
When I have to create a new table, I open another empty database and attach the relevant databases to the connection. When the operation is finished, I switch the old and the new connection. Code as follows:
#include <iostream>
#include "dbAccess.h"
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
bool inProgress = true;
DWORD WINAPI createTempTableThread(void *param);
int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
cout << "*";
return 0;
}
int main(void)
{
sqlite3* db = NULL;
HANDLE hThreadHandle = NULL;
CdbAccess *dba = new CdbAccess();
int i = 0;
db = dba->dbaConnect();
dba->dbaSetDatabase(db);
cout << "INFO: Creating initial temporary table. " << endl;
sqlite3_exec(dba->dbaGetDatabase(), "CREATE TEMPORARY TABLE temp_table AS " \
"SELECT * FROM pb.name_table " \
"LEFT JOIN pb.phone_table ON (pb.name_table.id=pb.phone_table.id) " \
"LEFT JOIN pb.email_table ON (pb.name_table.id=pb.email_table.id) " \
"UNION SELECT * FROM intern.name_table " \
"LEFT JOIN intern.phone_table ON (intern.name_table.id=intern.phone_table.id) " \
"LEFT JOIN intern.email_table ON (intern.name_table.id=email_intern.table.id);", NULL, NULL, NULL);
cout << "INFO: Creating initial temporary table finished. " << endl;
while(1)
{
hThreadHandle = CreateThread(0, 0, createTempTableThread, dba, 0, 0);
while(inProgress)
{
sqlite3_exec(dba->dbaGetDatabase(), "SELECT * FROM name_table WHERE id LIKE 1;", callback, NULL, NULL);
}
for(i = 0; i < 5; i++)
{
sqlite3_exec(dba->dbaGetDatabase(), "SELECT * FROM name_table WHERE id LIKE 2;", callback, NULL, NULL);
}
inProgress = true;
CloseHandle(hThreadHandle);
}
dba->dbaDisconnect();
return 0;
}
CdbAccess::CdbAccess()
{
hSemaphore = CreateSemaphore(NULL, 1, 1, 0);
}
CdbAccess::~CdbAccess()
{
}
sqlite3 *CdbAccess::dbaConnect()
{
sqlite3 *db;
static int num = 1;
int err = SQLITE_OK;
string attach = "ATTACH DATABASE \"";
string internal = "cbInternal.db";
if(num == 1)
{
cout << endl << "INFO: cbTemp1.db";
err = sqlite3_open("cbTemp1.db", &db);
num = 2;
}
else
{
cout << endl << "INFO: cbTemp2.db";
err = sqlite3_open("cbTemp2.db", &db);
num = 1;
}
if(err == SQLITE_OK)
{
cout << endl << "INFO: Temp database opened.";
err = sqlite3_exec(db, "ATTACH DATABASE \"cbInternal.db\" AS intern;", NULL, NULL, NULL);
if(err == SQLITE_OK)
{
cout << endl << "INFO: Internal database attached.";
err = sqlite3_exec(db, "ATTACH DATABASE \"0123456789.db\" AS pb;", NULL, NULL, NULL);
if(err == SQLITE_OK)
{
cout << endl << "INFO: Phone book attached.";
}
else
{
cout << endl << "ERROR: Attaching phone book: " << sqlite3_errmsg(db);
}
}
else
{
cout << endl << "ERROR: Attaching internal database: " << sqlite3_errmsg(db);
}
}
else
{
cout << endl << "ERROR: Opening database: " << sqlite3_errmsg(db);
}
return db;
}
int CdbAccess::dbaDisconnect(void)
{
int err = SQLITE_OK;
err = sqlite3_exec(db, "DETACH DATABASE pb;", NULL, NULL, NULL);
if(err == SQLITE_OK)
{
cout << endl << "INFO: Phone book detached.";
err = sqlite3_exec(db, "DETACH DATABASE intern;", NULL, NULL, NULL);
if(err == SQLITE_OK)
{
cout << endl << "INFO: Internal database detached.";
err = sqlite3_close(db);
if(err == SQLITE_OK)
{
cout << endl << "INFO: Database connection closed.";
}
else
{
cout << endl << "ERROR: Could not close database: " << sqlite3_errmsg(db);
}
}
else
{
cout << endl << "ERROR: Could not detach internal database: " << sqlite3_errmsg(db);
}
}
else
{
cout << endl << "ERROR: Could not detach phone book: " << sqlite3_errmsg(db);
}
return err;
}
sqlite3* CdbAccess::dbaGetDatabase(void)
{
return db;
}
void CdbAccess::dbaSetDatabase(sqlite3 * sqldb)
{
db = sqldb;
}
int CdbAccess::dbaGetTempTableAccess(void)
{
cout << endl << "INFO: Access requested.";
WaitForSingleObject(hSemaphore, INFINITE);
return 0;
}
int CdbAccess::dbaReleaseTempTableAccess(void)
{
cout << endl << "INFO: Access released.";
ReleaseSemaphore(hSemaphore, 1, NULL);
return 0;
}
DWORD WINAPI createTempTableThread(void *param)
{
int err = SQLITE_OK;
CdbAccess *d = (CdbAccess *)param;
sqlite3 *db;
cout << endl << "INFO: createTempTable: IN";
inProgress = true; // global variable for test porpose only
db = d->dbaConnect();
if(db != NULL)
{
cout << endl << "Thread: INFO: Creating temporary table. ";
err = sqlite3_exec(db, "CREATE TEMPORARY TABLE temp_table AS " \
"SELECT * FROM pb.name_table " \
"LEFT JOIN pb.phone_table ON (pb.name_table.id=pb.phone_table.id) " \
"LEFT JOIN pb.email_table ON (pb.name_table.id=pb.email_table.id) " \
"UNION SELECT * FROM intern.name_table " \
"LEFT JOIN intern.phone_table ON (intern.name_table.id=intern.phone_table.id) " \
"LEFT JOIN intern.email_table ON (intern.name_table.id=intern.email_table.id);", NULL, NULL, NULL);
}
if(err != SQLITE_OK)
{
cout << endl << "Thread: ERROR: Creating temporary table: " << sqlite3_errmsg(db);
}
else
{
cout << endl << "Thread: INFO: Creating temporary table finished. ";
}
d->dbaSetDatabase(db);
inProgress = false; // global variable for test porpose only
cout << endl << "Thread: INFO: createTempTable: OUT";
return 0;
}

MongoDB C++ driver not throwing connection error

Here is my code-
DBClientBase *conn = NULL;
string err_msg;
ConnectionString cs = ConnectionString::parse(connString, err_msg);
if (!cs.isValid()) {
throw "bad: " + err_msg;
}
try {
conn = cs.connect(err_msg);
}
catch (DBException &e) {
cout << "caught " << err_msg << endl;
return 1;
}
if (!conn) {
cout << "Unable to connect to DB" << endl;
return 1;
}
I would expect MongoDB to throw exception in case DB is not reachable. However, I am finding that if (!conn) is getting satisfied.
Why
catch (DBException &e) {
cout << "caught " << err_msg << endl;
return 1;
}
block isn't working?
From the current trunk source, ConnectionString::connect only seems to throw an exception when the string itself was invalid (and you already know that it was not, from your first conditional statement).
It just returns a NULL pointer and sets errMsg in all other cases.
In your defence, I couldn't find this documented anywhere at all; a very basic example of connect was all I could locate.
string err_msg;
ConnectionString cs = ConnectionString::parse(connString, err_msg);
if (!cs.isValid()) {
throw "bad: " + err_msg;
}
DBClientBase* conn = cs.connect(err_msg);
if (!conn) {
cout << "Unable to connect to DB: " << err_msg << endl;
return 1;
}

How to set autoreconnect option with mysql connector c++

Greetings, how can i set autoReconnect option with mysql connector c++ ?
( not with mysql c api http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html )
I am not a user of this library, so my knowledge of it is only that last 10 mins worth, so please do verify.
As a general rule, the best resource of such information about usage of various specific details of a library is to take a look at its unit tests. The best thing about OSS.
So if you look at MySQL Connector/C++ unit tests that can be found on their source tree, you will see the below extract.
sql::ConnectOptionsMap connection_properties;
...
connection_properties["OPT_RECONNECT"]=true;
try
{
con.reset(driver->connect(connection_properties));
}
catch (sql::SQLException &e)
{
std::cerr << e.what();
}
For more information, please do the below, so that you can take a look yourselves.
~/tmp$ bzr branch lp:~mysql/mysql-connector-cpp/trunk mysql-connector-cpp
~/tmp$ vi mysql-connector-cpp/test/unit/classes/connection.cpp +170
~/tmp$ vi mysql-connector-cpp/test/unit/classes/connection.h
Having said all that, reconnect option in mysql has to be used very carefully, as you will have to reset any session variables, etc. You will have to treat a reconnected connection as a brand new connection. This has to be verified with the documentation of the particular version of MySQL you are working with.
A more complete example
header
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
std::string host_name = "localhost";
std::string user_name = "user1234";
std::string password = "pw1234";
std::string database_name = "TestingDB";
bool reconnect_state = true;
sql::ConnectOptionsMap connection_properties;
sql::Driver *driver;
boost::shared_ptr <sql::Connection> con;
boost::shared_ptr <sql::Statement> stmt;
boost::shared_ptr <sql::ResultSet> res;
boost::shared_ptr <sql::PreparedStatement> pstmt;
connect
driver = get_driver_instance (); // protected
con.reset(driver->connect (host_name, user_name, password)); // connect to mysql
con->setClientOption("OPT_RECONNECT", &reconnect_state);
con->setSchema(database_name);
thread
std::vector <std::string> database::string_from_sql (std::string query, std::string column_name)
{
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | started" << std::endl;
std::vector <std::string> svec;
try
{
driver->threadInit(); // prevents multiple open connections
if (con.get() == NULL)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | connection is not open" << std::endl;
throw -2;
}
stmt.reset (con->createStatement ());
res.reset (stmt->executeQuery (query));
while (res->next())
{
svec.push_back(res->getString (column_name));
}
driver->threadEnd();
}
catch (sql::SQLException &e)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | e.what(): " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )" << std::endl;
throw -1;
}
if (svec.empty())
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | return vector size is 0 (Empty set)" << std::endl;
throw -3;
}
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | ended" << std::endl;
return svec;
}
You need to pass the boolean value by reference. My code does:
bool myTrue = true;
con->setClientOption("OPT_RECONNECT", &myTrue);
And that worked for me.