Kuroyuki Hikari
Kuroyuki Hikari

Reputation: 541

QT mysql doesnt open database

Hi2,

Does anyone know whats wrong with this code?

I want to connect the MySQL database with Qt program in Linux Ubuntu.
I use XAMPP for the mysql. I have make sure that the name, pass, port, database name are all right. And the mysql in xampp is starting.

However, it just keeps not opening. When i tried the same code in Windows, it works just fine

void MainWindow::CreateDatabaseConnection()
{

  QSqlDatabase db;
  db = QSqlDatabase::addDatabase("QMYSQL");
  db.setHostName("localhost");
  db.setUserName("root");
  db.setPassword("");
  db.setPort(3306);
  db.setDatabaseName("myDatabase");

  //test connection
  if(db.open())
      qDebug()<<"database connected ";
  else
      qDebug()<<"database failed to connect ";

  qDebug() << db.lastError();
}

ok i add the "db.lastError", the console output now says:

database failed to connect QSqlError("2002", "QMYSQL: Unable to connect", "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")


Have anyone encounter the same problem?

Upvotes: 0

Views: 882

Answers (1)

Kuroyuki Hikari
Kuroyuki Hikari

Reputation: 541

I dont know why but after i changed this line to

db.setHostName("localhost");

into

db.setHostName("127.0.0.1");

It can connect properly.
Can someone please explain this why it works with 127.0.0.1 but not with localhost...?
I have both of them configured in PHPmyadmin.

Upvotes: 1

Related Questions