How keep connection with MySQL Server 5
-
During the execution of long-read data needed to communicate with the database server. Continuous check of connection to the server is required to insert a large number of records.
Please advise how to check the connection and how to deal with situations where one loses the connection to the database server
I can often cause the following code:
@
static QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","Connection-To-MySQLServer-5.5");
static QSqlQuery query(db);db.setHostName("localhost"); db.setPort(3306); db.setUserName("root"); db.setPassword("root"); db.setDatabaseName("DataFromBinFiles"); if(!db.open()) { MessageBox (hwnd, "---", "Lost Connection", MB_OK|MB_ICONINFORMATION); return FALSE; } else { MessageBox (hwnd, "---", "Success", MB_OK|MB_ICONINFORMATION); return TRUE; }
@
-
Your code has nothing to do with losing a connection. It's only creating a connection and either succeeding or failing.
If an existing connection is lost between your machine and the server then queries will start failing. The QSqlQuery::lastError() call should return an error of type QSqlError::ConnectionError. You can also periodically check QSqlDatabase::isOpen(). Since you are using MySQL you can also use the MYSQL_OPT_RECONNECT in QSqlDatabase::setConnectOptions() to automatically attempt reconnection (it might still fail).
How you recover, if possible at all, is dependent on your application. If you have been working inside a transaction the server has probably already rolled back the transaction so you need to recover at that point in your application's processing.