Reputation: 1
#include <iostream>
#include <sstream>
#include <string>
#include <mysql_connection.h>
#include <mysql_driver.h>
#include <mysql_error.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
using namespace std;
using namespace sql;
using namespace mysql;
int main()
{
Connection* con = nullptr;
MySQL_Driver *driver = get_mysql_driver_instance();
const SQLString server = "server.de";
const SQLString user = "userName";
const SQLString password = "password";
while (1)
{
try {
con = driver->connect(server, user, password);
}
catch (SQLException e) {
printf("Fehler SQL Connect: %s \n", e.getSQLStateCStr());
delete driver;
}
catch (...) {
cerr << "Fehler SQL Connnect" << endl;
}
if (con)
{
con->close();
delete con;
}
boost::detail::Sleep(5000);
}
return 0;
}
I wrote this code and hoped it would run in an endless loop even, if the connect statement failed. What happens is: After the first time the connect failes it goes to the first catch statement and writes "Fehler SQL Connect: HY000" as I expect. The next time the connect failes the program breakes and in VS2017 I see 'te923021119.exe has triggered a breakpoint' Why doesn't the program try to connect endlessly? ncb
Upvotes: 0
Views: 91
Reputation: 403
In your exception handled you call delete driver;
This call destroys the driver object. It is not clear if it the right thing to do - as it is not clear if get_mysql_driver_instance()
gives you the ownership of a dynamically allocated object with new
.
But regardless - in the next iteration your program attempts to use driver
- which has been destroyed.
So - methinks don't call delete driver;
. Better yet - use smart pointers to communicate ownership semantic clearly. std::unique_ptr may be a good option.
Upvotes: 1