I would have determined the columns in the table thus:
for (int col = 0; col < record.count(); ++col)
qDebug() << col << record.fieldName(col); // or use QSqlField if you need types etc
QSqlDatabase db = QSqlDatabase::database();
QSqlRecord record = db.record("tablename");
for (int col = 0; col < record.count(); ++col)
qDebug() << col << record.fieldName(col); // or use QSqlField if you need types etc
To copy to clipboard, switch view to plain text mode
I would expect Qt to simply report precisely the order the database engine gives it the columns. However, I read in
QSqlDatabase::record() that this should not be relied on. The code I see for the Mysql driver should preserve order; perhaps others are different.
On the database end each column has an ordinal position within its table (from the user perspective) and a "SELECT * FROM T" query should return the columns from the table in "the ascending sequence of their ordinal position within T" to be standards compliant. See ANSI SQL-92
"7.9 <query specification>". Perhaps you could try a QSqlQuery with this query to see if you get a different ordering. There might be some non-compliance/quirks on RDBMS systems that permit "ALTER TABLE T ADD COLUMN blah" at arbitrary positions in the column order.
In general, you should not write code that depends on implied column order or assumes columns do not change if at all possible. Always name all columns in SELECT and INSERT and you will be glad when you have to maintain the code later.
Bookmarks