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.

Re: Qt remote database connection 80 80

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?

Re: Qt remote database connection 80 80

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

Re: Qt remote database connection 80 80

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.

Re: Qt remote database connection 80 80

Thank you richieking. I will look into that.

Re: Qt remote database connection 80 80
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 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.