我在使用C ++创建与MySQL数据库的连接这一简单任务时遇到了麻烦。除程序返回值(-1)外,不会打印错误。
我使用Eclipse Oxygen作为IDE,操作系统是Ubuntu 16.04。 MySQL连接器版本是1.1.9。它是通用的Linux版本(glibc 2.12)。
连接器文件位于我的主文件夹中。我已经添加了" include"的目录路径。文件夹到属性 - > C / C ++ Build - >设置 - > GCC C ++编译器 - >包括。我还添加了" lib"路径和" mysqlcppconn"库名称为Properties - > C / C ++ Build - >设置 - > GCC C ++链接器 - >库和库搜索路径分别。最后,我添加了" lib"路径进入属性中的LD_LIBRARY_PATH环境变量 - >运行/调试设置 - > (启动配置) - >环境。
DBManager.cpp:
DBManager::DBManager() {
try {
std::cout << "Getting driver instance" << std:endl;
driver = sql::mysql::get_mysql_driver_instance();
std::cout << "Creating connection" << std::endl;
connection = driver->connect("tcp://127.0.0.1:3306", "username", "password");
std::cout << "Connected!" << std::endl; // NOT REACHING THIS LINE
} catch(const SQLException& ex) {
// these lines are not printed
std::cout << "Exception!" << std::endl;
std::cout << ex.what() << std::endl;
exit(1);
}
}
DBManager::~DBManager() {
std::cout << "Deleting connection" << std::endl;
delete connection;
}
DBManager.h
#ifndef DBMANAGER_H_
#define DBMANAGER_H_
#include <iostream>
#include <mysql_connection.h>
#include <mysql_driver.h>
#include <cppconn/exception.h>
class DBManager {
public:
DBManager();
virtual ~DBManager();
private:
sql::mysql::MySQL_Driver* driver;
sql::Connection* connection;
};
#endif
的main.cpp
#include <iostream>
#include "DBManager.h"
int main(int argc, char* argv[]) {
std::cout << "Starting" << std::endl;
DBManager* dbManager = new DBManager();
// ... program logic not reached
delete dbManager; // not reached
return 0;
}