I am new to Qt and I'm trying to connect a remote database.

QSqlDatabase db = QSqlDatabase::addDatabase( "QMYSQL" );

  db.setHostName("IP ADRESS"); // local or IP
  db.setPort(3306); // Default port is 3306
  db.setUserName("DB USER"); // example root
  db.setPassword("PASSWORD");
  db.setDatabaseName("DB NAME");

  if( !db.open() )
  {
    qDebug() << db.lastError();
    qFatal( "Failed to connect." );
  }

  qDebug( "Connected!" );

  QSqlQuery qry;

  qry.prepare( "CREATE TABLE IF NOT EXISTS data (id INTEGER UNIQUE PRIMARY KEY, firstname VARCHAR(30), lastname VARCHAR(30))" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug() << "Table created!";

    ... goes on

this code works like a charm in local but when i give my server ip instead of localhost i can not connect. Should i use a different mechanism?

PS:I've never retrieved data from web before.

Are the values you put in lines 3-7 correct for the server you are trying to access (I assume you just posted dummy values here) ? Can you connect to the server manually?

i can connect the server via ssh and the values are dummy.

You can not simply connect to your database on another system like that.
There must be a contact or a server on the remote system that you will use to open the way to the inner operation.
This is simply done by running a server on the remote system that will connect to your app and via the connection have access to the DB.
Look into sockets and clients howtos.

So in short, there must be a server and a client.
Besides this there is no way to just connect to remote DB like what you want. Well i stand to be corrected but i am pretty confident with my answer as i have done this numerous times.

Thank you richieking. I will look into that.

qDebug() << db.lastError();

What's the error message from the above statement?

You may want to use the following to print the message...

cout << db->lastError().text() << "\n";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.