mardi 27 septembre 2016

Connecting to MySQL in C++

I am trying to learn to C++ and I having a bit of nightmare doing a test where I connect to a MySQL database.

I've had issues with the MySQL connector not linking properly then was getting issues related to relocation truncated to fitr_x86_64_32 against symbol.

I think I have fixed that by adding a compiler flag and now the app successfully build and links.

When I run the app, it gets as far as calling get_driver_instance but then it exits. No exception is thrown, no errors nothing just exit code 0.

Below is my DBManager class

#include "DBConnectionManager.h"

using namespace std;

DBConnectionManager::DBConnectionManager() {
    cout << "Starting DBConnectionManager - Updated" << endl;
    try {
        cout << "Getting driver instance" << endl;
        driver = get_driver_instance();
        cout << "Got driver instance" << endl;
        conn = driver->connect("tcp://127.0.0.1:3306", "root", "54mCuw901");
        conn->setSchema("bugs");
        cout << "Connected to database" << endl;
    }
    catch (SQLException ex) {
        cout << "Error connecting to DB: " << ex.what() << endl;
    }
    catch (...) {
        cout << "Something has gone wrong" << endl;
    }
}

Below is the header file

#ifndef MYSQLTEST_DBCONNECTIONMANAGER_H
#define MYSQLTEST_DBCONNECTIONMANAGER_H
#include <driver.h>
#include <exception.h>
#include <resultset.h>
#include <statement.h>

using namespace sql;

class DBConnectionManager
{
private:
    sql::Driver *driver;
    sql::Connection *conn;
    sql::Statement *statement;
    sql::ResultSet *res;
public:
    DBConnectionManager();
    void performSql();
};
#endif //MYSQLTEST_DBCONNECTIONMANAGER_H

Below is my CMakeLists.txt file

cmake_minimum_required(VERSION 3.6)
project(MySQLTest)

include_directories("C:\\Program Files\\MySQL\\MySQL Connector C++ 1.1.7\\include\\cppconn" "C:\\Program Files\\MySQL\\MySQL Connector C++ 1.1.7\\lib\\opt")

SET(GCC_COVERAGE_LINK_FLAGS    "-m64 -Wl,--image-base -Wl,0x10000000 -lpthread -pthread")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -m64 -Wl,--image-base -Wl,0x10000000 -lpthread -pthread ")

set(SOURCE_FILES main.cpp DBConnectionManager.cpp)
add_executable(MySQLTest ${SOURCE_FILES})
add_library(mysqlcppconn.lib)

set_target_properties(MySQLTest PROPERTIES LINKER_LANGUAGE CXX)
set_target_properties(mysqlcppconn.lib PROPERTIES LINKER_LANGUAGE CXX)

target_link_libraries(MySQLTest "C:\\Program Files\\MySQL\\MySQL Connector C++ 1.1.7\\lib\\opt\\mysqlcppconn.lib")

When I create the instance of my DBConnectionManager class it successfully calls the query and prints Starting DBConnectionManager - Updated followed by Getting Driver Instance but then it exits with Process finished with exit code 0 with no clues as to what went wrong.

Thanks for any help you can provide.

Aucun commentaire:

Enregistrer un commentaire