C ++ Mysql ++, connection always fail!
Steps:
- Installed Mysql Server 2005
- Loaded Mysql ++, built both debug and release.
- Ran install.hta and directory selected
- Added library / include directory in MSVC ++ 2008
- Enabled mysql ++. H in my application
- Move the DLL files (libMYSQL.dll and mysqlpp.dll and mysqlpp_d.dll) to the Debug folder.
Relevant code:
#include "mysql++.h"
class Database {
private:
mysqlpp::Connection* conn;
public:
~Database();
bool Connect(char* ip, char* user, char* pass, char* db);
};
bool Database::Connect(char* ip, char* user, char* pass, char* db) {
conn = new mysqlpp::Connection(false);
return conn->connect(db, ip, user, pass);
}
Database::~Database() {
if(conn) {
delete[] conn;
}
}
Problem:
Database db;
db.Connect("127.0.0.1", "root", "mypassword", "mydb");
This will always fall back to false even if I use the same with the credentials with MySQL admin and log it correctly.
Reference: (
I would not make this pointer:
mysqlpp::Connection* conn;
Just make it a normal class member.
mysqlpp::Connection conn;
This has several advantages.
But the most important thing for you is that you avoid the shallow copy problem.
Rule 4:
If an object is the owner of a RAW pointer, you need to define the following 4 members to ensure that you are handling memory management correctly:
* Constructor
* Copy Constructor
* Assignment Operator
* Destructor
This is because if you don't define them, the compiler will automatically generate the above methods for you. This works in most situations, but if your object contains a RAW pointer that you own (i.e., you delete it), then everything will be terribly wrong if generated by the compiler with these methods.
source to share
Also I would use strings rather than char pointers:
bool Database::Connect(char* ip, char* user, char* pass, char* db)
Try:
Database::Database(std::string const& ip,
std::string const& user,
std::string const& pass,
std::string const& db)
Note by moving the code from the Connect () method to the constructor (), you can make the object always valid.
source to share