I am using Qt to connect to databases (So far using PostgreSQL and mySQL) and am a little confused on how the ports work. I am using Ubuntu if that makes a difference.
According to the documentation here: http://doc.qt.nokia.com/4.8-snapshot/qsqldatabase.html#setPort there is no default value for ports. However I noticed on my settings that I don’t actually set a port but it is still connecting without a problem.
So I have it set up like this:
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("mydb");
db.setUserName("name");
db.setPassword("pass");
Which works (I have tried with mySQL driver too)
It also works if i do this: db.setPort(-1); or as I would expect using the default port: db.setPort(5432);
But other ports don’t work which is as expected. So, given it says there is no default port value and -1 is obviously not a valid port how does it work?
Qt itself may not provide a default port value, but the individual drivers do. When you
openvia Qt, it simply calls theopenof the driver-specific code.For example, the Postgress driver code contains the following
openfunction:Similarly, the driver code for MySQL passes
(port > -1) ? port : 0as the port parameter tomysql_real_connect(), meaning that a value of-1is translated to0. And, as any MySQL coder will tell you, that informsmysql_real_connect()to use the default port.In other words, a port is translated from the QT-generic default of
-1to whatever the specific driver requires as a suitable default (such as 3306 for MySQL, 50000 (or 60000) for DB2, and so on).If you do set it, it’s passed to the driver as is.