MySQL Forums
Forum List  »  Connector/C++

persistent connection problem
Posted by: D P
Date: October 04, 2011 12:56PM

I am trying to make a connection to MySQL on WinXP that persists across the full execution time of my Win32 app. I am doing something like LISTING 1 below.

I call MySQLInit when the app loads, and then MySQLExec whenever I need to work with the database, using the ResultSet pointer returned as needed before deleting it. When the app exits, I call MySQLClose.

To make the connection persistent, I instantiate the connection pointer in MySQLInit and don't delete it until MySQLClose. The problem with this code is that it leads to random crashes and exceptions (2013 lost connection, 2006 server gone away, 2027 malformed packet, etc.)

In case the connection is timing out, I tried deleting and reinstantiating the connection every 10 or 20 seconds, but it didn't help.

The code in LISTING 2 below is more like what I've seen in tutorials, and it works stable and consistent. What am I missing? Is there something bad about having the connection pointer as a global variable instead of a local that is allocated only for one SQL query execution? Thanks for any help.

LISTING 1
---------
sql::Driver *driver;
sql::Connection *con;

void MySQLInit(void) {
try {
driver = get_driver_instance();
con = driver->connect("tcp://localhost:3306", "root", "root");
con->setSchema("test");
}
catch (sql::SQLException &e) {
// exception stuff
}
}

sql::ResultSet *MySQLExec(const char *pszCmd) {
sql::Statement *stmt;
sql::ResultSet *res;

try {
stmt = con->createStatement();
res = stmt->executeQuery(pszCmd);
}
catch (sql::SQLException &e) {
// exception stuff
}

delete stmt;
return res;
}

void MySQLClose(void) {
try {
delete con;
}
catch (sql::SQLException &e) {
// exception stuff
}
}

LISTING 2
---------
sql::Driver *driver;

void MySQLInit(void) {
try {
driver = get_driver_instance();
}
catch (sql::SQLException &e) {
// exception stuff
}
}

sql::ResultSet *MySQLExec(const char *pszCmd) {
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;

try {
con = driver->connect("tcp://localhost:3306", "root", "root");
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery(pszCmd);
}
catch (sql::SQLException &e) {
// exception stuff
}

delete stmt;
delete con;
return res;
}



Edited 1 time(s). Last edit at 10/04/2011 12:59PM by D P.

Options: ReplyQuote


Subject
Views
Written By
Posted
persistent connection problem
2930
D P
October 04, 2011 12:56PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.