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.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();
    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.

2 Years
Discussion Span
Last Post by BobS0327

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?

Edited by Ancient Dragon


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.

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";
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.