views:

418

answers:

5

Steps:
- Installed Mysql Server 2005
- Downloaded Mysql++, built both debug and release version.
- Ran install.hta and selected a directory
- Added library/include directory in MSVC++ 2008
- Included mysql++.h in my application
- Moved .dll files (libMYSQL.dll and mysqlpp.dll and mysqlpp_d.dll) to 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 return to false, even though I am using the exact same credentials with MySQL Administrator and logging in correctly.

Help :(

A: 

I seem to have opened a thread too fast again :) I had a little typo in my database name (case sensitive).

New question:
I'm relatively new to C++ and OOP, would this be the prefered method of using the mysql++ library?

A: 

There's scripting languages that can do some fancy stuff with sql databases (I used php with my forum database), but I think what you have setup is an excellent way of proceeding.

Mark Essel
+2  A: 

I would not make this pointer:

mysqlpp::Connection* conn;

Just make it a normal member of the class.

mysqlpp::Connection conn;

This has several advantages.
But the most important to you is that you will avoid the shallow copy problem.

Rule of 4:

If an object is the owner of a RAW pointer then you need to define the following 4 members to make sure you handle the memory management correctly:

* Constructor
* Copy Constructor
* Assignment Operator
* Destructor

This is because if you do not define them the compiler will automatically generate the above methods for you. In most situations these work, but if your object contains a RAW pointer that you own (ie you delete it) then things will go horibly wrong witht he compiler generated version of these methods.

Martin York
A: 

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 method Connect() to the constructor() you can make the object always valid.

Martin York
Wouldn't this result in an unnecessary creation of std::string objects when called with a string literal, eg db.Connect("127.0.0.1", "me", "passwd", "db") ? I'd make the parameters const char* in this case.
AndrewR
A: 

can you past what the error message is? this problem should be simple and the error message can point out the road.

Allopen