Passing strings as arguments
Mar 17, 2011 at 12:41am UTC
I'm getting weird runtime behavior with the MySQL C++ connector. I've narrowed the problem down but have no idea what's happening.
header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#ifndef DATABASE_H__
#define DATABASE_H__
#include <string>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
using namespace std;
using namespace sql;
class Database
{
string url, schema, user, pass;
struct Driver* driver;
struct Connection* con;
bool connect();
public :
Database(string url, string schema, string user, string pass);
};
#endif
source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include "stdafx.h"
#include "Database.h"
using namespace std;
using namespace sql;
Database::Database(string url, string schema, string user, string pass)
:url(url), schema(schema), user(user), pass(pass)
{
if (connect())
{
con->setSchema(schema);
}
}
bool Database::connect()
{
try
{
cout << "TEST: " << url << endl;
driver = get_driver_instance();
con = driver->connect(url, user, pass);
return true ;
}
catch (SQLException &e)
{
cout << "Database::connect: " << e.what() << endl;
return false ;
}
}
If I create a Database object in the main function and pass it a URL, username and password like so...
Database* db = new Database("tcp://localhost:3306" , "root" , "root" );
This is what I get during runtime...
TEST: tcp://localhost:3306
Database::connect: Unknown MySQL server host '©yñ' (11004)
Press any key to continue . . .
As you can see, '©yñ' is not what I passed into the constructor. However if I modify the Database::connect() method...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
bool Database::connect()
{
try
{
cout << "TEST: " << url << endl;
driver = get_driver_instance();
con = driver->connect("tcp://localhost:3306" , "root" , "root" ); //modified this line
return true ;
}
catch (SQLException &e)
{
cout << "Database::connect: " << e.what() << endl;
return false ;
}
}
Everything seems to work fine. Does anyone know what's going on here? I'm using VC++ for this.
Last edited on Mar 17, 2011 at 12:55am UTC
Mar 17, 2011 at 3:33am UTC
Update: I googled for a bit and found out that this issue might have had something to do with the character encoding. I got around it by passing each string's contents as an array of characters instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
bool Database::connect()
{
try
{
driver = get_driver_instance();
con = driver->connect(url.data(), user.data(), pass.data()); //call data() function for each string
return true ;
}
catch (SQLException &e)
{
cout << "Database::connect: " << e.what() << endl;
return false ;
}
}
Last edited on Mar 17, 2011 at 3:38am UTC
Topic archived. No new replies allowed.